Thursday, September 27, 2007

The Evils of the while(true) loop

There has been a disgusting tendency among some alleged programmers to write an endless loop as:

while (true) {
// do something
}

rather than the classic:

for (;;) {
// do something smarter than the above loop
}

The first form is not only an abuse of logic but an abuse of notation. Logically it suggests a loop that will go on forever because of some tautology--which has absolutely nothing to do with the logic of the program--used as its condition. In pseudocode:

while (all Greeks are Men) {
...
if (pigs can fly)
break;
}

In other words the condition in the while statement has nothing to do with the condition for exiting the loop. It is an abuse of notation since a while loop is really a syntactic sugar for the more general for loop in which a condition is expected to be false at some time during its execution.

Now, consider the beautiful, elegant:

for (;;) {
}

not only is it much more succinct than the former, but there is no need for some bogus condition for the loop check expression. It simply and clearly states that a loop will continue to iterate until some internal condition dictates that it is now time to break out.