Structure and flow of control in a for loop
suggest changefor ([declaration-or-expression]; [expression2]; [expression3])
{
/* body of the loop */
}
A for statement has three clauses, and each one may be omitted. Omitting the test treats it as true, so for (;;) does not stop on its own. A declaration in the first clause is a C99 feature.
- The first clause,
declaration-or-expression, initializes the loop. It is executed exactly once, before the first test.
It is either a declaration or an expression. A variable declared there has scope limited to the for statement, including its body. C89 allowed only an expression, so the variable had to be declared before the for.
- The second clause,
expression2, is the test. It runs after the initialization and after each update. If it compares unequal to 0, the body runs. If it compares equal to 0, the loop ends. This is the usual way to leave a loop.break,goto, andreturnare the others; see Jump Statements.continuein aforloop jumps to the update clause, not back to the test. - The third clause,
expression3, is the update. It runs after the body and before the next test. It often increments a variable that counts iterations. That variable is called an iterator. It does not run on an iteration that never reaches it, including when the test fails before the first body.
Each instance of execution of the loop body is called an iteration.
Example:
for(int i = 0; i < 10 ; i++)
{
printf("%d", i);
}
The output is:
0123456789
In the example, i = 0 runs first. The test i < 10 is then true, so the body prints i. Then i++ changes i from 0 to 1 and the test runs again. This continues until i is 10. That test is false, so the loop ends. The snippet needs <stdio.h> for printf. i is not modified in the body; if it were, the trip count would change.