The general differentiating factor between the following loops:
while (condition) {action}
do {action} while (condition)
is that the former is used for loops that happen zero or more times whilst the latter is for loops that happen one or more time.
In other words, the condition for while
is checked at the start of the loop, and for do while
, it's checked at the end.
Often you'll see code where the developers don't seem to know about do-while
in that they'll write:
result = doSomething();
while (result == NOT_FINISHED) {
result = doSomething();
}
which could be better written as:
do {
result = doSomething();
} while (result == NOT_FINISHED);
However, in your specific case where the condition is always true
, it doesn't really matter. The following loops are basically equivalent (using 1
for the true case):
for (;;) { doSomething(); }
for (;;doSomething());
while (1) { doSomething(); }
do { doSomething(); } while (1);
while (doSomething(),1);
BADPAX: doSomething(); goto BADPAX;
The first for
loop is probably the canonical way of doing an infinite loop, taking advantage of the fact that, if you omit the continuation condition for the loop, it assumes it to be always true.
The second for
loop is just moving the loop body into the per-iteration part of the for
statement.
The first while
is also sometimes seen in the wild, the do-while
probably less so. The only distinction here is that the former loops forever checking at the loop top, the latter loops forever checking at the loop bottom.
The final while
loop is using the C comma operator in a way you probably never should :-)
That last one is very rare nowadays but is probably what they all optimise down to at the machine code level.