Cpp - Statement for Statement

Initializing and Reinitializing

A typical loop uses a counter that is initialized, tested by the controlling expression and reinitialized at the end of the loop.

int count = 1;                     // Initialization 
while( count <= 10)                // Controlling 
{                                 // expression 
   cout << count 
        << ". loop" << endl; 
   ++count;                        // Reinitialization 
} 

In a for loop statement the elements that control the loop can be found in the loop header.

The above example can also be expressed as a for loop:

int count; 
for( count = 1; count <= 10; ++count) 
   cout << count << ". loop" << endl; 

Any expression can be used to initialize and reinitialize the loop.

A for loop has the following form:

for( expression1; expression2; expression3 ) 
      statement 
  • expression1 is executed first and only once to initialize the loop.
  • expression2 is the controlling expression, which is always evaluated prior to executing the loop body
  • if expression2 is false, the loop is terminated
  • if expression2 is true, the loop body is executed. Subsequently, the loop is reinitialized by executing expression3 and expression2 is re-tested.

Any of the three expressions in a for statement can be omitted.

You must type at least two semicolons. The shortest loop header is therefore:

for(;;) 

This statement causes an infinite loop, since the controlling expression is assumed to be true if expression2 is missing. In the following

for( ; expression; ) 

the loop header is equivalent to while(expression). The loop body is executed as long as the test expression is true.

Related Topic