Namespaces
Variants
Views
Actions

for loop

From cppreference.com
 
 
C++ language
General topics
Preprocessor
Comments
Keywords
ASCII chart
Escape sequences
History of C++
Flow control
Conditional execution statements
Iteration statements
for loop
range-for loop (C++11)
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

Executes a loop.

Used as a more readable equivalent of while loop.

Contents

[edit] Syntax

for ( init_expression ; cond_expression ; iteration_expression ) loop_statement

[edit] Explanation

The above syntax produces code equivalent to:

{
init_expression ;
while ( cond_exression ) {
loop_statement
iteration_expression ;
}

}

The init_expression is executed before the execution of the loop. The cond_expression 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 loop_statement is executed on each iteration, after which iteration_expression 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.

[edit] Keywords

for

[edit] Example

#include <iostream>
 
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 << " ";
    }
}

Output:

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