Looping forever and ever

2008-09-08, , Comments

alex-bug

On the subject of syntactic sugar, C’s for loop is a curious beast. Many years ago, on encountering code like:

for (i = 0; i < 10; i++)
{
    ....
}

I would have to pause and mentally expand it:

i = 0;
while (i < 10)
{
    ....
    i++;
}

Now, after repeated use, these loops seem familiar and expressive. While the standard C++ algorithms offer a higher level abstraction with their iterator range operations, plain old loops often turn out to be easier to work with.

You can plug general expressions into the loop control construct.

for (<setup>; <proceed?>; <advance>)
{
    ....
}

Any or all of the control expressions can be omitted: drop the <setup> if nothing needs setting up; leave out the <advance> if nothing needs advancing; and kill the <proceed?> to keep the loop going. Thus one standard form of never-ending loop is:

for (;;)
{
    ....
}

Equivalents would be while (1) or while (true), but who wants to see a bald literal in a source file? Besides, for (;;) is shorter than while (1), and an empty while () is of course a syntax error. Even better: use a suitable font, squint, and the parenthesised semicolons resemble a mite of some sort.

Scary mite dust mite