I have seen some very weird for loops when reading other people’s code. I have been trying to search for a full syntax explanation for the for loop in C but it is very hard because the word ‘for’ appears in unrelated sentences making the search almost impossible to Google effectively.
This question came to my mind after reading this thread which made me curious again.
The for here:
for(p=0;p+=(a&1)*b,a!=1;a>>=1,b<<=1);
In the middle condition there is a comma separating the two pieces of code, what does this comma do? The comma on the right side I understand as it makes both a>>=1 and b<<=1.
But within a loop exit condition, what happens? Does it exit when p==0, when a==1 or when both happen?
It would be great if anyone could help me understand this and maybe point me in the direction of a full for loop syntax description.
The comma is not exclusive of for loops; it is the comma operator.
will do first a, then b, then set x to the value of b.
The for syntax is:
Which is somewhat (ignoring
continueandbreakfor now) equivalent to:So your for loop example is (again ignoring
continueandbreak) equivalent toWhich acts as if it were (again ignoring
continueandbreak):Two extra details of the for loop which were not in the simplified conversion to a while loop above:
true(resulting in an infinite loop unless abreak,goto, or something else breaks the loop).continueacts as if it were a goto to a label just before the increment, unlike acontinuein the while loop which would skip the increment.Also, an important detail about the comma operator: it is a sequence point, like
&&and||(which is why I can split it in separate statements and keep its meaning intact).Changes in C99
The C99 standard introduces a couple of nuances not mentioned earlier in this explanation (which is very good for C89/C90).
First, all loops are blocks in their own right. Effectively,
is itself wrapped in a pair of braces
The standard sayeth:
This is also described in the Rationale in terms of the extra set of braces.
Secondly, the
initportion in C99 can be a (single) declaration, as inNow the ‘block wrapped around the loop’ comes into its own; it explains why the variable
icannot be accessed outside the loop. You can declare more than one variable, but they must all be of the same type:The standard sayeth: