for循环中的逗号

3
为什么以下代码会产生错误?
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++。

3
相关链接:https://dev59.com/r3A75IYBdhLWcg3wW3u8,似乎引用了早期的https://dev59.com/CnE95IYBdhLWcg3wXsyR,该问题似乎是这个问题的一个很好的复制。 - dmckee --- ex-moderator kitten
2个回答

15

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

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

2
很遗憾的是,没有办法将一些声明设置为“const”,而将另一些声明保持不变。 - seh
16
@seh: for ( struct { int anything; const int you; float want;} data = {5, 10, 3.14f}; ...; ...)这行代码是一个for循环的头部,其中定义了一个名为"data"的结构体变量,并初始化了它的成员变量"anything"、"you"和"want"。在循环执行期间,你可以在循环体中使用"data"变量。 - GManNickG
1
@seh @strager: :) 我同意这有点丑陋,我可能不会在真正的代码中这样做(到目前为止还没有),但这是一种方法。更容易的方法是在循环上面定义变量。 - GManNickG

4

在一个正常的程序中:

int main()
{

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

}

这样做永远不会起作用,也不被接受。

这实际上是你在for循环内部尝试做的事情!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接