tags:

views:

303

answers:

6

Why is this not valid

for( int i = 0, int x = 0; some condition; ++i, ++x )

and this is

int i, x;
for( i = 0, x = 0; some condition; ++i, ++x )

Thanks

+4  A: 

Correct version is

for (int i = 0, x = 0; some condition; ++i, ++x)
stas
+14  A: 

this works:

for( int i = 0, x = 0; some condition; ++i, ++x )

it's like a variable declaration:

int i, j; // correct
int i, int j; // wrong, must not repeat type
sergiom
In fact, it _is_ a variable declaration. To be precise, both are `simple-declaration` s
MSalters
+3  A: 

Because a variable declaration (like int x) is not an expression and the comma operator (,) only combines expressions.

sth
This exposes a sad limitation of the for loop initialisation block. i.e. All variables initialised in the initialisation block must be the same type.
Michael Anderson
Almost: `for(int x, *y; ...`
MSalters
Beware, the `,` in the declaration `int x, y;` is NOT the comma operator!
FredOverflow
+6  A: 

Why should it be valid? It is a syntactically meaningless construst. What were you trying to say with it?

The first part of for header is a declaration. The

int i = 0, int x = 0

is not a valid declaration. It will not compile in for for the same reason why it won't compile anywhere else in the program

int i = 0, int x = 0; // Syntax error

When you need to declare two objects of type int in one declaration, you do it as follows

int i = 0, x = 0; // OK

The same thing can be used in for

for( int i = 0, x = 0; some condition; ++i, ++x )  

(But when you need to declare two variables of different types, it can't be done by one declaration and, therefore, both cannot be declared in for at the same time. At least one of them will have to be declared before for.)

AndreyT
+2  A: 

This is legal:

    for(int i = 0, x = 0; condition; ++i, ++x );

int x, int y is not a legal way of declaring variables;

Arve
+2  A: 

when you need to declare two variables of different types, it can't be done by one declaration

Hackety hack hack:

for (struct {int i; char c;} loop = {0, 'a'}; loop.i < 26; ++loop.i, ++loop.c)
{
    std::cout << loop.c << '\n';
}

;-)

FredOverflow
Wow! Never heard of this before.
sharptooth