The forStatement 55
Multiple Expressions
You can include multiple expressions in any of the fields of the forloop, provided that
you separate such expressions by commas. For example, in the forstatement that begins
for ( i = 0, j = 0; i < 10; ++i )
...
the value of iis set to 0 andthe value of jis set to 0 before the loop begins.The two
expressions i = 0and j = 0are separated from each other by a comma, and both
expressions are considered part of the init_expressionfield of the loop. As another
example, the forloop that starts
for ( i = 0, j = 100; i < 10; ++i, j = j - 10 )
...
sets up two index variables,iand j; the former initialized to 0 and the latter to 100
before the loop begins. Each time after the body of the loop is executed, the value of i
is incremented by 1, whereas the value of jis decremented by 10.
Omitting Fields
Just as the need might arise to include more than one expression in a particular field of
the forstatement, the need might arise to omitone or more fields from the statement.
This can be done simply by omitting the desired field and marking its place with a semi-
colon.The most common application for the omission of a field in the forstatement
occurs when there is no initial expression that needs to be evaluated.The
init_expressionfield can simply be “left blank” in such a case, as long as the semi-
colon is still included:
for ( ; j != 100; ++j )
...
This statement might be used if jwere already set to some initial value before the loop
was entered.
A forloop that has its looping_conditionfield omitted effectively sets up an infi-
nite loop; that is, a loop that is theoretically executed forever. Such a loop can be used
provided there is some other means used to exit from the loop (such as executing a
return,break, or gotostatement as discussed elsewhere in this book).
Declaring Variables
You can also declare variables as part of your initial expression inside a forloop.This is
done using the normal ways you’ve defined variables in the past. For example, the fol-
lowing can be used to set up a forloop with an integer variable counterboth defined
and initialized to the value 1 :
for ( int counter = 1; counter <= 5; ++counter )