Skip to content

Range-Based for Loop (C++11) ​

In a nutshell ​

Syntactic sugar that lets us iterate over every element of a container or array without hand-writing iterators, making loop code more concise and less error-prone.

Header file ​

None (language feature)

Core API Cheat Sheet ​

OperationSignatureDescription
Read-only traversalfor (auto item : range)Copies each element into item
Reference traversalfor (auto& item : range)Accesses elements via lvalue reference (modifiable)
Const reference traversalfor (const auto& item : range)Avoids copies and prevents modification
Init statementfor (init; auto& item : range)Runs initialization before the loop starts (since C++20)
Array traversalfor (auto item : arr)Works with native arrays of known size

Minimal Example ​

C++
#include <vector>
#include <iostream>
// Standard: C++11
int main() {
    std::vector<int> v = {1, 2, 3};
    for (const auto& x : v) {
        std::cout << x << ' ';
    }
    return 0;
}

Embedded Applicability: High ​

  • Zero-overhead abstraction: compiles to code fully equivalent to a hand-written iterator or index loop, with no extra runtime cost
  • The concise syntax cuts down on bugs caused by out-of-bounds indices or invalidated iterators
  • Also very practical for compile-time traversal of constexpr arrays
  • Caution: when the range comes from a member function returning a temporary, watch out for lifetime issues (UB before C++23)

Compiler Support ​

GCCClangMSVC
4.63.02012

See Also ​


Part of the content is referenced from cppreference.com and is licensed under CC-BY-SA 4.0

pdf-latest-4-g85128cc · 85128cc · 2026-10-05