Skip to content

Range-based for Loop (C++11)

In a Nutshell

Syntactic sugar that allows us to traverse all elements of a container or array without manually writing iterators, making loop code more concise and less error-prone.

None (language feature)

Core API Quick Reference

OperationSignatureDescription
Read-only traversalfor (auto item : container)Copies each element to item
Reference traversalfor (auto& item : container)Accesses elements via lvalue reference (mutable)
Const reference traversalfor (const auto& item : container)Avoids copying and prevents modification
Initialization statementfor (init; auto& item : container)Executes initialization before the loop (since C++20)
Array traversalfor (auto& item : array)Supports native arrays of known size

Minimal Example

Expand (29 lines)Collapse
cpp
#include <vector>
#include <iostream>

int main() {
    std::vector<int> data = {1, 2, 3, 4, 5};

    // Read-only traversal (copies elements)
    for (auto val : data) {
        std::cout << val << " ";
    }
    // Output: 1 2 3 4 5

    // Reference traversal (modifies elements)
    for (auto& val : data) {
        val *= 2;
    }

    // Const reference traversal (avoids copying)
    for (const auto& val : data) {
        std::cout << val << " ";
    }
    // Output: 2 4 6 8 10

    // C++20: Initialization statement
    for (auto idx = 0; const auto& val : data) {
        std::cout << idx << ": " << val << "\n";
        ++idx;
    }
}

Embedded Applicability: High

  • Zero-overhead abstraction: Compiles to code equivalent to hand-written iterator or index loops, with no extra runtime cost.
  • Concise syntax reduces errors caused by out-of-bounds indices or invalid iterators.
  • Very practical for compile-time traversal of std::array when combined with constexpr.
  • Note: Be cautious of lifetime issues when traversing member functions that return temporary objects (this is UB prior to C++23).

Compiler Support

GCCClangMSVC
4.63.02010

See Also


Part of the content references cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05