views:

209

answers:

2
+2  Q: 

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++.

+11  A: 

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)
siride
And it's disappointing that there's no means to make some of the declarations `const` and some of them not.
seh
your last ; should be a ,
Juliano
@seh: `for ( struct { int anything; const int you; float want;} data = {5, 10, 3.14f}; ...; ...)`
GMan
Clever, GMan. Clever indeed.
seh
But now it's ugly to access.
strager
@Juliano I fixed the mistake
siride
@seh @strager: :) I agree it's a bit ugly, I probably wouldn't do it in real code (haven't so far), but it is a way. Far easier just to define the variables above the loop.
GMan
+3  A: 

In a normal program:

int main()
{

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

}

will never work and is not accepted.

This is what you are actually trying to do inside the for loop!

Vijay Sarathi