逗号循环中的逗号

Var*_*nce 3 c++ for-loop comma-operator

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

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
Run Code Online (Sandbox Code Playgroud)

编译器是g ++.

sir*_*ide 13

每个语句只能有一种类型的声明,所以你只需要一个int:

for(int i = 0, pos = 0, next_pos = 0; i < 3; i++, pos = next_pos + 1)
Run Code Online (Sandbox Code Playgroud)

  • @seh:`for(struct {int anything; const int you; float want;} data = {5,10,3.14f}; ...; ...)` (15认同)
  • 你最后一次 ; 应该是, (6认同)
  • 但是现在访问它很难看. (3认同)
  • 并且令人失望的是,没有办法制作一些声明`const`而其中一些没有. (2认同)