The idiom designed into the C language (and inherited into C++) for infinite looping is for(;;)
: the omission of a test form. The do/while
and while
loops do not have this special feature; their test expressions are mandatory.
for(;;)
does not express "loop while some condition is true that happens to always be true". It expresses "loop endlessly". No superfluous condition is present.
Therefore, the for(;;)
construct is the canonical endless loop. This is a fact.
All that is left to opinion is whether or not to write the canonical endless loop, or to choose something baroque which involves extra identifiers and constants, to build a superfluous expression.
Even if the test expression of while
were optional, which it isn't, while();
would be strange. while
what? By contrast, the answer to the question for
what? is: why, ever---for ever! As a joke some programmers of days past have defined blank macros, so they could write for(ev;e;r);
.
while(true)
is superior to while(1)
because at least it doesn't involve the kludge that 1 represents truth. However, while(true)
didn't enter into C until C99. for(;;)
exists in every version of C going back to the language described in the 1978 book K&R1, and in every dialect of C++, and even related languages. If you're coding in a code base written in C90, you have to define your own true
for while (true)
.
while(true)
reads badly. While what is true? We don't really want to see the identifier true
in code, except when we are initializing boolean variables or assigning to them. true
need not ever appear in conditional tests. Good coding style avoids cruft like this:
if (condition == true) ...
in favor of:
if (condition) ...
For this reason while (0 == 0)
is superior to while (true)
: it uses an actual condition that tests something, which turns into a sentence: "loop while zero is equal to zero." We need a predicate to go nicely with "while"; the word "true" isn't a predicate, but the relational operator ==
is.