`for` — C++ Keyword

`for` — C++ Keyword

The for keyword in C++: traditional counted loop and range-based for loop.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

for

Executes a body repeatedly. C++ provides both the traditional three-part for loop and the range-based for loop (C++11).

Syntax

// Traditional
for (init-statement; condition; iteration-expression) statement

// Range-based (C++11)
for (range-declaration : range-expression) statement

// Range-based with initializer (C++20)
for (init-statement; range-declaration : range-expression) statement

Example

#include <print>
#include <vector>

int main() {
    // Traditional counted loop
    for (int i = 0; i < 5; ++i) {
        std::print("{} ", i);   // 0 1 2 3 4
    }
    std::println();

    // Range-based for loop
    std::vector<int> v = {10, 20, 30};
    for (int x : v) {
        std::print("{} ", x);  // 10 20 30
    }
    std::println();

    // Range-based with initializer (C++20)
    for (auto& data = v; int x : data) {
        std::print("{} ", x);
    }
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}