C++ Syntax: for
Description
The for loop corresponds roughly to the FORTRAN do loop. The syntax is:-
for ( init-expr; test-expr; increment-expr) statement
any or all of the expressions insides the brackets may be empty.
The sequence is as follows:-
- init-expr, if it exists, is executed. Typically this initialises
one or more counters, and may also declare them as well.
- test-expr is evaluated. If it evaluates to true (nonzero) or is
missing then statement, which is often a
compound statement
is executed. Otherwise the for loop exits.
- increment-expr is executed if it exists. Typically this
increments one or more counters.
- Control returns to step 2 and the test repeated.
For example to sum the contents the 10 element array my_ints:-
Int_t sum = 0;
for (Int_t index=0; index<10; index++) sum += my_ints[index];
Usage Notes
When init-expr is used to declare, as well as initialise a variable, it
is defined to have the same
scope
as the for statement itself, that is to say the innermost compound statement
that holds the for loop. Two important consequences:-
To break out of a loop use the
break
statement and to skip directly to the next cycle of a loop use the
continue
statement.
Go Back to the
The C++ Crib Top Page
If you have any comments about this page please send them to
Nick West