David Bowling David Bowling - 1 year ago 45
C Question

Why do for(;;) loops behave like infinite loops?

The answers to the recent question about

loops did not seem to answer something for me, so I thought that I would try to refine the question a bit. In the statement
for (;_;){}
, the
is a conditional expression. My first guess would be that an empty expression might evaluate to
. But if you test:

for (;;){}

is an infinite loop, as everyone has pointed out.

for (;1;){}

is an infinite loop.

But neither of these loop bodies execute at all:

for (;0;){}
for (;NULL;){}

Thus, the empty conditional expression does not seem to evaluate to either

So, my question: is the behavior of the
for (;;){}
loop an artifact of the way that C evaluates expressions, or is it just a special implementation-defined case, because a loop body that never executes is not very useful?

Answer Source

Both C and C++ guarantee this behaviour.

[C99:]: Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.

[C++14: 6.5.3/1]: The for statement

for ( for-init-statement conditionopt; expressionopt) statement

is equivalent to

   while ( condition ) {
      expression ;


[C++14: 6.5.3/2]: Either or both of the condition and the expression can be omitted. A missing condition makes the implied while clause equivalent to while(true).