The for statement can be divided into three separate parts, as shown in Table 5.3.
Table 5.3 for Loop Elements
Syntax Name | When Executed | Contents |
for-init-statement | Before any other element of the for statement or the substatement. | Often used to initialize loop indices. It can contain expressions or declarations. |
expression1 | Before execution of a given iteration of the loop, including the first iteration. | An expression that evaluates to an integral type or a class type that has an unambiguous conversion to an integral type. |
expression2 | At the end of each iteration of the loop; expression1 is tested after expression2 is evaluated. | Normally used to increment loop indices. |
The for-init-statement is commonly used to declare and initialize loop-index variables. The expression1 is often used to test for loop-termination criteria. The expression2 is commonly used to increment loop indices.
The for statement executes the statement repeatedly until expression1 evaluates to zero. The for-init-statement, expression1, and expression2 fields are all optional.
The following for loop:
for( for-init-statement; expression1; expression2 )
{
// Statements
}
is equivalent to the following while loop:
for-init-statement;
while( expression1 )
{
// Statements
expression2
}
A convenient way to specify an infinite loop using the for statement is:
for( ; ; )
{
// Statements to be executed.
}
This is equivalent to:
while( 1 )
{
// Statements to be executed.
}
The initialization part of the for loop can be a declaration statement, or any other type of statement, including the null statement. The initializations can include any sequence of expressions and declarations, separated by commas. Any object declared inside a for-init-statement has local scope, as if it had been declared immediately prior to the for statement. While the name of the object can be used in more than one for loop in the same scope, the declaration can appear only once. For example:
int main()
{
for( int i = 0; i < 100; ++i )
cout << i << "\n";
// The loop index, i, cannot be declared in the
// for-init-statement here because it is still in scope.
for( i = 100; i >= 0; --i )
cout << i << "\n";
return 0;
}
Although the three fields of the for statement are normally used for initialization, testing for termination, and incrementing, they are not restricted to these uses. For example, the following code prints the numbers 1 to 100. The substatement is the null statement:
#include <iostream.h>
int main()
{
for( int i = 0; i < 100; cout << ++i << "\n" )
;
return 0;
}