Pages

5.03.2014

Beware of commas in For loops

In a C like language, we can declare a for loop as such:
for(pre; condition; post)
where "pre" is something that happens before the loop starts, "condition" is a check that happens before each run of the loop, and "post" happens after each time through the loop. We can get even more fancy and do more than one of each of these. For example, we could have this:
for(pre1, pre2; cond1, cond2; post1, post2)

In this case, "pre1" and "pre2" happen before the loop, "cond1" and "cond2" are evaluated before each run of the loop, and "post1" and "post2" happen after each run of the loop.

Be careful however when placing commas between the conditions.  This may cause unexpected behavior in your program.  When conditions are separated by commas, they are evaluated as OR.  This would be the same as cond1 OR cond2. In my recent C programming adventures, I spent a non-trivial amount of time tracking down this misbehavior. Eventually, I changed the comma to the explicit AND operator and everything worked as expected.  For those interested, the line was as follows:

This causes problems:
for(i = 0; i < index, cur != head; i++, cur = cur->next);
This works the way I want:
for(i = 0; i < index && cur != head; i++, cur = cur->next);