Why can the condition of a for-loop be left empty?

c, c++, for-loop

Solution

http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

These are the iteration statements

while ( expression ) statement

do statement while ( expression ) ;

for ( expression [opt] ; expression [opt] ; expression [opt] ) statement

for ( declaration expression [opt] ; expression [opt] ) statement

The while loop was designed to evaluate the controlling expression before each execution of the loop and the do loop was designed to evaluate after each execution.

The for loop was designed as a more sophisticated iteration statement.

6.8.5.3 The for statement

The statement

for ( clause-1 ; expression-2 ; expression-3 ) statement

behaves as follows: The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body. The expression expression-3 is evaluated as a void expression after each execution of the loop body. If clause-1 is a declaration, the scope of any identifiers it declares is the remainder of the declaration and the entire loop, including the other two expressions; it is reached in the order of execution before the first evaluation of the controlling expression. If clause-1 is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.

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

The specification allows expression-2, the condition of the loop, to be omitted and is replaced by a nonzero constant. This means that the for loop will continue to execute indefinitely.

This is useful for allowing a simple syntax for iterating with no end.

for(int i = 0;;i++) { //do stuff with i }

That's much simpler to write and understand than writing a while(1) loop with a variable declared outside the loop and then incremented inside the loop.

The for loop specification then goes on to allow you to omit clause-1 so that you can declare or initialize variables elsewhere, and you can omit expression-3 so that you are not required to evaluate any expression upon completion of each loop.

The for loop is a special case. The while loop and the do loop are strict and require an expression, but the for loop is a flexible iteration statement.

Problem

Possible Duplicate: No loop condition in for and while loop Why is the condition in a `for-loop` allowed to be left empty? For example ``` for (;;) ``` compiles fine. Why does this empty expression evaluate to `true` but the following ``` if () {} while () {} ``` will both fail? I want to know if/why the `for-loop` is an exception to this case.

Original source

Related problems