Reputation: 15062
I´ve seen a a few times already in answers and questions here on Stack Overflow, a comma-separated list as loop condition for a for-loop like : for(int i = 0, int j = 0 ; i < 2, j < 4; i++, j++) { ... }
. How does this work?
How does a comma-separated condition work in a for-loop in C?
Like:
for(int i = 0, int j = 1 ; i < 5, j < 4; i++, j++) { ... }
Isn´t this invalid because the condition needs to be an evaluated expression? How do the multiple comma-separated expressions get evaluated to one expression in the for-loop?
The mentioned expressions are enclosed by semicolons ; i < 5, j < 4;
, and this shall be the condition of the loop. Or am I wrong?
Upvotes: 3
Views: 965
Reputation: 1434
All the expressions in the comma-separated list are evaluated, but only the last expression is used for the for loop condition. So in effect the i<5 condition is ignored, since it's not the last expression.
Upvotes: 1
Reputation: 60107
The syntax for a for
loop with a declaration is (6.8.5):
for ( declaration expression_opt ; expression_opt ) statement
This
for(int i = 0, int j = 1 ; i < 5, j < 4; i++, j++) { }
doesn't parse because
int i = 0, int j = 1 ;
isn't syntactically valid as a declaration (or any sentential form in C for that matter) but
for(int i = 0, j = 1; i < 5, j < 4; i++, j++) { }
would parse, because
int i = 0, j = 1;
is a valid declaration (with multiple, initializer-containing declarators) and
i < 5, j < 4
is a valid comma-operator-containing expression, as is
i++, j++
.
(Note that i < 5, j < 4
has the same effect as just j < 4
because comma expressions are evaluated left to right and the value of the final part is used, and since i < 5
has no side-effect here, the whole expression is equivalent to just j < 4
. You might have wanted i < 5 && j < 4
instead.)
In the original form of the for
loop (without a declaration) you have (6.8.5)
for ( expression_opt ; expression_opt ; expression_opt ) statement
and the semicolons are used to separate the 3 (optional) expressions.
In the declaration-containing form, the first semicolon is parsed as part of the declaration
for ( declaration expression_opt ; expression_opt ) statement
.
Upvotes: 8