The C for Statement

The for statement lets you repeat a statement or compound statement a specified number of times. The body of a for statement is executed zero or more times until an optional condition becomes false. You can use optional expressions within the for statement to initialize and change values during the for statement’s execution. 

Syntax

iteration-statement :

for ( init-expression opt ; cond-expression opt ; loop-expression opt ) statement

Execution of a for statement proceeds as follows:

  1. The init-expression, if any, is evaluated. This specifies the initialization for the loop. There is no restriction on the type of init-expression.

  2. The cond-expression, if any, is evaluated. This expression must have arithmetic or pointer type. It is evaluated before each iteration. Three results are possible:
    • If cond-expression is true (nonzero), statement is executed; then loop-expression, if any, is evaluated. The loop-expression is evaluated after each iteration. There is no restriction on its type. Side effects will execute in order. The process then begins again with the evaluation of cond-expression.

    • If cond-expression is omitted, cond-expression is considered true, and execution proceeds exactly as described in the previous paragraph. A for statement without a cond-expression argument terminates only when a break or return statement within the statement body is executed, or when a goto (to a labeled statement outside the for statement body) is executed.

    • If cond-expression is false (0), execution of the for statement terminates and control passes to the next statement in the program.

A for statement also terminates when a break, goto, or return statement within the statement body is executed. A continue statement in a for loop causes loop-expression to be evaluated. When a break statement is executed inside a for loop, loop-expression is not evaluated or executed. This statement

for( ;; );

is the customary way to produce an infinite loop which can only be exited with a break, goto, or return statement.

This example illustrates the for statement:

for ( i = space = tab = 0; i < MAX; i++ ) 
{
    if ( line[i] == ' ' )
        space++;
    if ( line[i] == '\t' ) 
    {
        tab++;
        line[i] = ' ';
    }
}

This example counts space (' ') and tab ('\t') characters in the array of characters named line and replaces each tab character with a space. First i, space, and tab are initialized to 0. Then i is compared with the constant MAX; if i is less than MAX, the statement body is executed. Depending on the value of line[i], the body of one or neither of the if statements is executed. Then i is incremented and tested against MAX; the statement body is executed repeatedly as long as i is less than MAX.