For Statement
The for
statement implements an iterative loop. The syntax of the for
statement is:
for ([init-expression]; [condition-expression]; [increment-expression]) statement
Before the first iteration of the loop, init-expression
sets the starting variables for the loop. You cannot pass declarations in init-expression
.
condition-expression
is checked before the first entry into the block; statement
is executed repeatedly until the value of condition-expression
is false. After each iteration of the loop, increment-expression
increments a loop counter. Consequently, i++
is functionally the same as ++i
.
All expressions are optional. If condition-expression
is left out, it is assumed to be always true. Thus, “empty” for
statement is commonly used to create an endless loop in C:
for ( ; ; ) statement
The only way to break out of this loop is by means of the break
statement.
Here is an example of calculating scalar product of two vectors, using the for
statement:
for ( s = 0, i = 0; i < n; i++ ) s += a[i] * b[i];
There is another way to do this:
for ( s = 0, i = 0; i < n; s += a[i] * b[i], i++ ); /* valid, but ugly */
but it is considered a bad programming style. Although legal, calculating the sum should not be a part of the incrementing expression, because it is not in the service of loop routine. Note that null statement (;
) is used for the loop body.
What do you think about this topic ? Send us feedback!