thecodex.expert · The Codex Family of Knowledge
C++

Control Flow

C required manual index bookkeeping for every single loop over a container — C++11’s range-based for loop eliminated nearly all of it, and eliminated an entire class of off-by-one bugs along with it.

C++20 / C++23 Range-based for since C++11 Last verified:
Canonical Definition

C++'s if, while, do-while, and classic for loops use the same syntax C does. The range-based for loop, added in C++11, iterates directly over any container (an array, a vector, a string) without manual index management, working with any type that provides begin()/end() iterators — which includes every standard container and is straightforward to add to custom types too. C++17 additionally allows if and switch statements to include an init-statement, scoping a helper variable to just that conditional block rather than leaking into the surrounding scope.

The classic, C-style for loop

This still works exactly as in C, and remains the right choice when the loop needs the index itself, not just each element.

C++classic_for.cpp
std::vector<int> numbers = {10, 20, 30, 40};

for (int i = 0; i < numbers.size(); i++) {
    std::cout << numbers[i] << " ";
}

Range-based for: no manual indexing at all (C++11+)

This iterates every element directly, with no index variable, no bounds to get wrong, and no off-by-one risk — auto& avoids copying each element, useful for larger element types.

C++range_for.cpp
std::vector<int> numbers = {10, 20, 30, 40};

for (auto n : numbers) {        // copies each element
    std::cout << n << " ";
}

for (auto& n : numbers) {      // reference — no copy, and can modify in place
    n *= 2;
}

if with an init-statement (C++17+)

result is scoped to ONLY the if/else block — it doesn't leak into the surrounding function, avoiding a common source of accidental name reuse in longer functions.

C++if_init.cpp
std::map<std::string, int> ages = {{"Alice", 30}};

if (auto it = ages.find("Alice"); it != ages.end()) {
    std::cout << it->second << "\n";   // it is scoped to just this if/else
}
// it is NOT accessible here — it went out of scope with the if statement

Sources

1
ISO/IEC 14882 (C++ Standard), "Range-based for loop" and "Selection statements," cppreference.com/w/cpp/language.