Namespaces
Variants
Views
Actions

for loop

From cppreference.com
< cpp‎ | language
Revision as of 23:44, 15 January 2013 by Bazzy (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements (loops)
for
range-for (C++11)
Jump statements
Functions
Function declaration
Lambda function declaration
inline specifier
Exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
decltype (C++11)
auto (C++11)
alignas (C++11)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Implicit conversions - Explicit conversions
static_cast - dynamic_cast
const_cast - reinterpret_cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
Miscellaneous
 

Executes a loop.

Used as a shorter equivalent of a while loop.

Contents

Syntax

for ( Template:sparam ; Template:sparam ; Template:sparam ) Template:sparam

Explanation

The above syntax produces code equivalent to:

{
Template:sparam ;
while ( Template:sparam ) {
Template:sparam
Template:sparam ;
}

}

The Template:sparam is executed before the execution of the loop. The Template:sparam shall evaluate to value, convertible to bool. It is evaluated before each iteration of the loop. The loop continues only if its value is true. The Template:sparam is executed on each iteration, after which Template:sparam is executed.

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.

Keywords

for

Example

#include <iostream>
#include <vector>
 
int main() 
{
    for (int i = 0; i < 10; i++) {
        std::cout << i << " ";
    }
 
    std::cout << '\n';
 
    for (int j = 2; j < 9; j = j + 2) {
        std::cout << j << " ";
    }
 
    std::cout << '\n';
 
    // Check also the new Range-based for loop (C++11)
    // for iterating with containers.
    std::vector<int> v = {3, 1, 4, 1, 5, 9};
    for (std::vector<int>::iterator iter = v.begin();
         iter != v.end();
         ++iter) {
        std::cout << *iter << " ";
    }
 
    std::cout << '\n';
}

Output:

0 1 2 3 4 5 6 7 8 9
2 4 6 8
3 1 4 1 5 9

See Also