Description |
 |
The for
statement is a general-purpose looping construct that allows you
to specify the initialization, termination, and increment of the
loop. The for
uses three expressions. Semicolons separate the expressions. Each
expression is optional, but you must include the semicolons.
Expression1 is the initialization
expression that typically specifies the initial values
of variables. It is evaluated only once before the first iteration
of the loop.
Expression2 is the controlling
expression that determines whether or not to terminate
the loop. It is evaluated before each iteration of the loop. If
expression2 evaluates to a nonzero value,
the loop body is executed. If it evaluates to 0, execution of the
loop body is terminated and control passes to the first statement
after the loop body. This means that if the initial value of expression2
evaluates to zero, the loop body is never executed.
Expression3 is the increment
expression that typically increments the variables initialized
in expression1. It is evaluated after
each iteration of the loop body and before the next evaluation of
the controlling expression.
The for
loop continues to execute until expression2
evaluates to 0, or until a jump statement, such as a break
or goto, interrupts
loop execution.
If the loop body executes a continue
statement, control passes to expression3.
Except for the special processing of the continue
statement, the for
statement is equivalent to the following:
expression1; while (expression2) { statement expression3; }
|
You may omit any of the three expressions. If expression2
(the controlling expression) is omitted, it is taken to be a nonzero
constant.
Example |
 |
For example:
for (i=0; i<3; i++) { func(i); }
|
This example calls the function func
three times, with argument values of 0, 1, and 2.