A for question

Recently, I’ve had the opportunity to stumble upon this for loop question in the Dream In Code forum. Appalling code aside, it took me awhile to convince myself that, yes, programming can be hard sometimes. Ok, let’s take a look at this excerpt from the original thread starter:

for (i=j+k;; j+k)
break;

He claimed it worked. While I think modern compilers would fail it, I seem to remember older compilers are a bit more forgiving. Particularly the j+k incrementor part. Basically, it’s like a single statement

j+k;

Doesn’t do anything. Sure it adds j and k together, but without doing anything with the result, it’s not useful. But it’s valid for the older compilers I’ve worked with.

Well, assuming it works, he just assigned the sum j+k to the variable i, do no loop checks, breaks immediately, and so doesn’t even hit the incrementor part. Did anyone notice anything yet?

He doesn’t need the for loop.

He could’ve just assigned j+k to i and be done with it.

To clear up the mystery of the for loop, we’ll take a value doubling example, so let’s study the following:

int i, sum;
sum = 1;
for (i = 0; i < 5; ++i)
{
    sum += sum;
}

There’s the multiply by 2 method. There’s the shift left by one placing method. I chose to simply add itself to itself in each iteration.

That was the standard for loop structure. Usually, the same variable appears in the initialiser part, the loop terminator part and the incrementor part.
for (initialiser; terminator; incrementor)

Here’s the short, one-liner version:

int i, sum;
for (i = 0, sum = 1; i < 5; ++i, sum += sum) ;

The incrementor part is just a place where any code is executed before the terminator condition is checked. Technically speaking, you can put any code here. But please don’t. There’s a proper place for whatever you can have in mind. It’s called the loop body.

How about using a while loop?

int i, sum;
i = 0;
sum = 1;
while (i < 5)
{
    sum += sum;
    ++i;
}

Note the incrementing code ++i is now at the end of the loop body. But the end result is equivalent to the for loops above.

Then there’s the do-while loop:

int i, sum;
i = 0;
sum = 1;
do
{
    sum += sum;
    ++i;
} while (i < 5);

do-while loops have this unique property. The loop body is executed at least once. It’s like “do loop body, then check condition”. The while loop works like “check condition, then do loop body”.

Because of this unique property, the following code

int i, sum;
i = 0;
sum = 1;
do
{
    sum += sum;
    ++i;
} while (i < 0);

ends up with the variable sum storing 2 instead of 1, even though the terminating condition is always false (hence it breaks from the loop immediately).

You might like to read up on my introductory article on for loops for more information.