Executes init-statement once, then executes statement and iteration_expression repeatedly, until the value of condition becomes false. The test takes place before each iteration.
Syntax
formal syntax: | ||
attr(optional) for ( init-statement condition(optional) ; iteration_expression(optional) ) statement | ||
informal syntax: | ||
attr(optional) for ( declaration-or-expression(optional) ; declaration-or-expression(optional) ; expression(optional) ) statement |
attr(C++11) | - | any number of attributes |
init-statement | - | either
; , which is why it is often described informally as an expression or a declaration followed by a semicolon. |
condition | - | either
|
iteration_expression | - | any expression, which is executed after every iteration of the loop and before re-evaluating condition. Typically, this is the expression that increments the loop counter |
statement | - | any statement, typically a compound statement, which is the body of the loop |
Explanation
The above syntax produces code equivalent to:
{
|
Except that.
while(true)
If the execution of the loop needs to be terminated at some point, break statement can be used as terminating statement.
If the execution of the loop needs to be continued at the end of the loop body, continue statement can be used as shortcut.
As is the case with while loop, if statement is a single statement (not a compound statement), the scope of variables declared in it is limited to the loop body as if it was a compound statement.
for(;;) int n; // n goes out of scope
Keywords
for
.
Notes
While in C++, the scope of the init-statement and the scope of statement are one and the same, in C the scope of statement is nested within the scope of init-statement:
for (int i = 0; ; ) { long i = 1; // valid C, invalid C++ // ... }
Example
#include <iostream> #include <vector> int main() { // typical loop with a single statement as the body for (int i = 0; i < 10; ++i) std::cout << i << ' '; std::cout << '\n'; // init-statement can declare multiple names, as long as they // can use the same decl-specifier-seq for (int i=0, *p = &i; i < 9; i+=2) { std::cout << i << ':' << *p << ' '; } std::cout << '\n'; // condition may be a declaration char cstr[] = "Hello"; for(int n = 0; char c = cstr[n]; ++n) std::cout << c; std::cout << '\n'; // init-statement can use the auto type specifier std::vector<int> v = {3, 1, 4, 1, 5, 9}; for (auto iter = v.begin(); iter != v.end(); ++iter) { std::cout << *iter << ' '; } std::cout << '\n'; // init-statement can be an expression int n = 0; for (std::cout << "Loop start\n"; std::cout << "Loop test\n"; std::cout << "Iteration " << ++n << '\n') if(n > 1) break; std::cout << '\n'; }
Output:
0 1 2 3 4 5 6 7 8 9 0:0 2:2 4:4 6:6 8:8 Hello 3 1 4 1 5 9 Loop start Loop test Iteration 1 Loop test Iteration 2 Loop test
See also
range-for loop | executes loop over range (since C++11) |
C documentation for for |
Please login to continue.