Structure and flow of control in a for loop

suggest change
for ([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.

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.

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents