Name

for

Synopsis

A typical for loop uses a control variable and performs the following actions on it:

  1. Initialization (once before beginning the loop)

  2. Tests the controlling expression

  3. Makes adjustments (such as incrementation) at the end of each loop iteration

The three expressions in the head of the for loop define these three actions.

Syntax:

for ([expression1]; [expression2]; [expression3]
         
                     statement

expression1 and expression3 can be any expressions. Expression2 is the controlling expression, and hence must have a scalar type. Any of these expressions can be omitted. If expression2 is omitted, the loop body is executed unconditionally. In ANSI C99, expression1 may also be a declaration. The scope of the variable declared is then limited to the for loop.

Example:

for (int i = DELAY; i > 0; --i)    // Wait a little
    ;

Except for the scope of the variable i, this for loop is equivalent to the following while loop:

int i = DELAY; // Initialize 
while( i > 0)  // Test the controlling expression
     --i; // Adjust

Get C Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.