Alex Rivera | Logout

What is the full "for" loop syntax in C?

Asked 2008-11-09T21:40:34.950
61

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.

Edit
Report

1 Answer

5

The C style for loop consists of three expressions:

for (initializer; condition; counter) statement_or_statement_block;
  • The initializer runs once, when the loop starts.
  • The condition is checked before each iteration. The loop runs as long it evaluates to true.
  • The counter runs once after each iteration.

Each of these parts can be an expression valid in the language you write the loop in. That means they can be used more creatively. Anything you want to do beforehand can go into the initializer, anything you want to do in between can go into the condition or the counter, up to the point where the loop has no body anymore.

To achieve that, the comma operator comes in very handy. It allows you to chain expressions together to form a single new expression. Most of the time it is used that way in a for loop, the other implications of the comma operator (e.g. value assignment considerations) play a minor role.

Even though you can do clever things by using syntax creatively - I would stay clear of it until I find a really good reason to do so. Playing code golf with for loops makes code harder to read and understand (and maintain).

The wikipedia has a nice article on the for loop as well.

answered 2008-11-09T21:57:58.580

Your Answer