Skip to content

Range-based for Loop (C++11)

One-Liner

Syntactic sugar for traversing 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 : range)Copies each element to 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)Executes initialization before the loop (since C++20)
Array traversalfor (auto item : arr)Supports native arrays of known size

Minimal Example

cpp
#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 down to code completely equivalent to hand-written iterator or index loops, with no extra runtime cost
  • Concise syntax reduces errors caused by out-of-bounds indexing or iterator invalidation
  • Combined with constexpr arrays, compile-time traversal is also very practical
  • 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


Some content referenced from cppreference.com, licensed under CC-BY-SA 4.0

Built with VitePress