Search code examples
c++for-loopcomma-operator

Commas in for loop


Why is the following line producing errors?

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

Compiler is g++.


Solution

  • You can have only one type of declaration per statement, so you only need one int:

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