for loop

< cpp‎ | language

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.


[edit] Syntax

attr(optional) for ( init-statement condition(optional) ; iteration_expression(optional) ) statement
attr(C++11) - any number of attributes
init-statement - either an expression statement or a declaration statement, typically a declaration of a loop counter variable with initializer. Note that an init-statement must end with a semicolon.
condition - any expression which is contextually convertible to bool or a declaration of a single variable with a brace-or-equals initializer. This expression is evaluated before each iteration, and if it yields false, the loop is exited. If this is a declaration, the initializer is evaluated before each iteration, and if the value of the declared variable converts to false, the loop is exited.
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

[edit] Explanation

The above syntax produces code equivalent to:

while ( condition ) {
iteration_expression ;


Except that

1) Names declared by the init-statement (if init-statement is a declaration) and names declared by condition (if condition is a declaration) are in the same scope.
2) continue in the statement will execute iteration_expression
3) Empty condition is equivalent to while(true)



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.

    int n;
// n goes out of scope

[edit] Keywords


[edit] Example

#include <iostream>
#include <vector>
int main()
    // typical loop with a single statement as the body
        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)
    std::cout << '\n';


0 1 2 3 4 5 6 7 8 9 
0:0 2:2 4:4 6:6 8:8 
3 1 4 1 5 9 
Loop start
Loop test
Iteration 1
Loop test
Iteration 2
Loop test

[edit] See Also