5.7 For

The for loop has the following syntax:

    for (initialization; condition; upgrade)
        statement


The elements between () require explanation.

initialization

This is an expression evaluated once at the beginning of the loop. This is usually used to initialize loop variables. The comma sequence operator, described in XXX, can be used to include several sub-expressions. For example, to initialize two loop variables i = 0, j = 1 could be used.

condition

This is an expression that is evaluated once before each iteration of the loop, after the initialization expression has been evaluated. The loop only proceeds as long as this condition is true. For example, i < 10 && j != 5.

upgrade

This is an expression that is evaluated after each iteration of the loop, before the condition expression is checked. It is usually used to increment or decrement counters. For example, i++, j = j + 2.

Is should be clear that the for loop is nearly equivalent to:

    <initialization>
    while (<condition>) {
        statement
        upgrade
    }
but is much more compact since both initialization, exit condition and upgrade code are in the same place. Another benefit of using a for loop is that if a continue statement is executed inside the loop (typically from within an if statement) it skips to the ``upgrade'' expression.

All three elements of the for loop are optional. For example the initialization can be skipped if none is required or if it's done before the loop. If the condition is skipped you must provide some other way to exit the loop (such as a break statement). Remember that even if you don't provide some of the elements you must still include the semi-colons as in:

    for (;;)
        statement


This, and other documents, can be downloaded from http://opencbp.sourceforge.net/.

For questions about the Open C Book Project, read the documentation.