【问题标题】:Commas in for loopfor循环中的逗号
【发布时间】:2025-11-30 23:50:01
【问题描述】:

为什么以下行会产生错误?

for(int i = 0, int pos = 0, int next_pos = 0; i < 3; i++, pos = next_pos + 1) {
  // …
}

error: expected unqualified-id before ‘int’
error: ‘pos’ was not declared in this scope
error: ‘next_pos’ was not declared in this scope

编译器是 g++。

【问题讨论】:

标签: c++ for-loop comma-operator


【解决方案1】:

每个语句只能有一种类型的声明,因此只需要一个 int:

for(int i = 0, pos = 0, next_pos = 0; i < 3; i++, pos = next_pos + 1)

【讨论】:

  • 令人失望的是没有办法做出一些声明 const 而其中一些没有。
  • @seh: for ( struct { int anything; const int you; float want;} data = {5, 10, 3.14f}; ...; ...)
  • @seh @strager: :) 我同意这有点难看,我可能不会在实际代码中这样做(到目前为止还没有),但这是一种方式。在循环上方定义变量要容易得多。
【解决方案2】:

在普通程序中:

int main()
{

int a=0,int b=0,int c=0;
return 0;    

}

永远不会工作,也不被接受。

这就是你在 for 循环中实际尝试做的事情!

【讨论】: