# Range-based for loop (since C++11)

> C++ Atlas: `cppatlas.com/w/cpp/language/range-for` | Source: https://en.cppreference.com/w/cpp/language/range-for | Domain: Language | Standards: C++17, C++20, C++23

Executes a for loop over a range.

## Executive Mental Model (Study Companion)

**Core Intuition:** Allocating bytes does not create an object, and freeing bytes is not what destroys one—lifetime begins at initialization and ends at destruction or storage reuse.

- **Standard Era:** C++11 → C++17 → C++20 → C++23
- **Primary ISO Clauses:** [basic.life], [basic.stc], [class.temporary], [stmt.ranged]
- **CppCon Talk Angle:** Show the two timelines side by side: storage duration (how long the bytes exist) vs. object lifetime (when the typed object is legally alive inside those bytes).
- **Common Audience Trap:** Assuming temporary lifetime extension propagates through accessor methods like auto& x = make_container().front(); inside range-for loops.
- **Stage Takeaway:** Use C++20 std::bit_cast instead of pointer-punning reinterpret_cast, and verify C++23 P2718 before trusting chained temporaries in range-for.

## Memory Map Walkthrough: Virtual Address Space & Scope Lifetime Scrubber

In C++, storage duration and object lifetime are distinct concepts. Storage duration governs when raw memory exists—static, thread-local, automatic on the stack, or dynamic on the heap—while object lifetime begins only when initialization completes and ends when the destructor starts or the storage is reused. Binding a temporary directly to a const lvalue reference or rvalue reference extends its lifetime to the reference's scope, but chaining through a member function or accessor stops lifetime extension cold, creating a classic dangling reference before C++23's range-for fix (P2718R0). Meanwhile, placement-new reusing storage that contained const or reference subobjects requires std::launder so the optimizer does not reuse cached values from the previous object.

### Storage duration is not object lifetime ([basic.life] §6.7.3)

When you allocate raw aligned storage (alignas(Widget) std::byte buf[sizeof(Widget)];), storage exists, yet zero Widget objects live there. Accessing a Widget* pointing to buf before placement-new construction is Undefined Behavior.

C++20 softened one long-standing C interop pain point with Implicit-Lifetime Types ([intro.object]): malloc or std::start_lifetime_as (C++23) can implicitly begin the lifetime of trivial aggregates/arrays so C network buffers no longer rely on theoretical UB.

*Why std::launder exists for const members:*
```cpp
struct Node { const int id; };
Node* p = new Node{1};
// Reuse p's storage with placement new:
new (p) Node{2};
// Compiler may legally assume p->id is STILL 1 because 'id' is const!
int safe_id = std::launder(p)->id; // Guaranteed 2 ([ptr.launder])
```

**Key takeaway:** Compilers track pointer provenance and const member immutability; std::launder tells the optimizer a fresh object replaced the old one at that address.

### Temporary lifetime extension & the range-for cliff ([class.temporary] & [stmt.ranged])

Writing const std::string& s = make_name(); extends the materialized temporary string to match s's scope. Write const char* p = make_name().c_str(); or auto& item : get_wrapper().items() in C++11–C++20, and the outer temporary wrapper is destroyed BEFORE the loop body even begins!

C++23 paper P2718R0 finally fixed range-based for loops by extending the lifetime of ALL temporaries in the range-initializer expression until the loop finishes—matching what every developer already assumed.

*Pre-C++23 range-for dangling temporary:*
```cpp
struct Wrapper { std::vector<int> items{1, 2, 3}; };
Wrapper make_wrapper();

// Pre-C++23: UB! Wrapper temporary dies before loop starts!
// C++23 (P2718R0): Well-defined! All temporaries in range-init extend across loop.
for (int v : make_wrapper().items) {
    use(v);
}
```

**Key takeaway:** Whenever a function returns a reference or view into a temporary receiver (std::string_view, std::span, or .items), check whether you are pre-C++23.

## Official Specification Summary (cppreference)

Executes a `for` loop over a range.

Used as a more readable equivalent to the traditional `for` loop operating over a range of values, such as all elements in a container.

### Syntax

- *attr* (optional) `for (` *init-statement* (optional) *item-declaration* `:` *range-initializer* `)` *statement*

- `attr` - any number of attributes
- `init-statement` - (since C++20) one of

  - an expression statement (which may be a null statement `;`)
  - a simple declaration (typically a declaration of a variable with initializer), it may declare arbitrarily many variables or be a structured binding declaration

  (since C++23):

  - an alias declaration

  Note that any *init-statement* must end with a semicolon. This is why it is often described informally as an expression or a declaration followed by a semicolon.
- `item-declaration` - a declaration for each range item
- `range-initializer` - an expression or brace-enclosed initializer list
- `statement` - any statement (typically a compound statement)

### Explanation

The above syntax produces code equivalent to the following except for the lifetime expansion of temporaries of *range-initializer* (see below) (since C++23) (the variables and expressions wrapped in `/* */` are for exposition only):

(until C++17):

`{`

  `auto&&` `/* range */` `=` *range-initializer* `;`

  `for (auto` `/* begin */` `=` `/* begin-expr */,` `/* end */` `=` `/* end-expr */;`

  `/* begin */` `!=` `/* end */; ++/* begin */)`

  `{`

  *item-declaration* `= */* begin */;`

  *statement*

  `}`

`}`

(since C++17) (until C++20):

`{`

  `auto&&` `/* range */` `=` *range-initializer* `;`

  `auto` `/* begin */` `=` `/* begin-expr */;`

  `auto` `/* end */` `=` `/* end-expr */;`

  `for (;` `/* begin */` `!=` `/* end */; ++/* begin */)`

  `{`

  *item-declaration* `= */* begin */;`

  *statement*

  `}`

`}`

(since C++20):

`{`

  *init-statement*

  `auto&&` `/* range */` `=` *range-initializer* `;`

  `auto` `/* begin */` `=` `/* begin-expr */;`

  `auto` `/* end */` `=` `/* end-expr */;`

  `for (;` `/* begin */` `!=` `/* end */; ++/* begin */)`

  `{`

  *item-declaration* `= */* begin */;`

  *statement*

  `}`

`}`

*range-initializer* is evaluated to initialize the sequence or range to iterate. Each element of the sequence, in turn, is dereferenced and is used to initialize the variable with the type and name given in *item-declaration*.

*item-declaration* can be one of the following:

- a simple declaration with the following restrictions:
- It has only one declarator.
- The declarator must have no initializer.
- The declaration specifier sequence can only contain type specifiers and `constexpr`, and it cannot define a class or enumeration.

Exposition-only expressions `/* begin-expr */` and `/* end-expr */` are defined as follows:

- If the type of `/* range */` is a reference to an array type `R`:

  - If `R` is of bound `N`, `/* begin-expr */` is `/* range */` and `/* end-expr */` is `/* range */ + N`.
  - If `R` is an array of unknown bound or an array of incomplete type, the program is ill-formed.

- If the type of `/* range */` is a reference to a class type `C`, and searches in the scope of `C` for the names “`begin`” and “`end`” each find at least one declaration, then `/* begin-expr */` is `/* range */.begin()` and `/* end-expr */` is `/* range */.end()`.
- Otherwise, `/* begin-expr */` is `begin(/* range */)` and `/* end-expr */` is `end(/* range */)`, where “`begin`” and “`end`” are found via argument-dependent lookup (non-ADL lookup is not performed).

If the loop needs to be terminated within *statement*, a `break` statement can be used as terminating statement.

If the current iteration needs to be terminated within *statement*, a `continue` statement can be used as shortcut.

If a name introduced in *init-statement* is redeclared in the outermost block of *statement*, the program is ill-formed:

```cpp
for (int i : {1, 2, 3})
    int i = 1; // error: redeclaration
```

### Temporary range initializer

If *range-initializer* returns a temporary, its lifetime is extended until the end of the loop, as indicated by binding to the forwarding reference `/* range */`.

Lifetimes of all temporaries within *range-initializer* are not extended unless they would otherwise be destroyed at the end of *range-initializer* (since C++23).

```cpp
// if foo() returns by value
for (auto& x : foo().items()) { /* ... */ } // until C++23 undefined behavior
```

(since C++20):

This problem may be worked around using *init-statement*:

```cpp
for (T thing = foo(); auto& x : thing.items()) { /* ... */ } // OK
```

(since C++23):

Note that even in C++23 non-reference parameters of intermediate function calls do not get a lifetime extension (because in some ABIs they are destroyed in the callee, not in the caller), but that is only a problem for functions that are buggy anyway:

```cpp
using T = std::list<int>;
const T& f1(const T& t) { return t; }
const T& f2(T t)        { return t; } // always returns a dangling reference
T g();

void foo()
{
    for (auto e : f1(g())) {} // OK: lifetime of return value of g() extended
    for (auto e : f2(g())) {} // UB: lifetime of f2's value parameter ends early
}
```

### Notes

If the *range-initializer* is a braced-enclosed initializer list, `/* range */` is deduced to be a reference to a `std::initializer_list`.

It is safe, and in fact, preferable in generic code, to use deduction to forwarding reference, `for (auto&& var: sequence)`.

The member interpretation is used if the range type has a member named “`begin`” and a member named “`end`”. This is done regardless of whether the member is a type, data member, function, or enumerator, and regardless of its accessibility. Thus a class like `class meow { enum { begin = 1, end = 2 }; /* rest of class */ };` cannot be used with the range-based `for` loop even if the namespace-scope “`begin`”/“`end`” functions are present.

While the variable declared in the *item-declaration* is usually used in the *statement*, doing so is not required.

As of C++17, the types of the `/* begin-expr */` and the `/* end-expr */` do not have to be the same, and in fact the type of the `/* end-expr */` does not have to be an iterator: it just needs to be able to be compared for inequality with one. This makes it possible to delimit a range by a predicate (e.g. "the iterator points at a null character"). (since C++17)

When used with a (non-const) object that has copy-on-write semantics, the range-based `for` loop may trigger a deep copy by (implicitly) calling the non-const `begin()` member function.

(since C++17):

If that is undesirable (for instance because the loop is not actually modifying the object), it can be avoided by using `std::as_const`:

```cpp
struct cow_string { /* ... */ }; // a copy-on-write string
cow_string str = /* ... */;

// for (auto x : str) { /* ... */ } // may cause deep copy

for (auto x : std::as_const(str)) { /* ... */ }
```

| Feature-test macro | Value | Std | Feature |
| --- | --- | --- | --- |
| `__cpp_range_based_for` | `200907L` | (C++11) | Range-based `for` loop |
| `__cpp_range_based_for` | `201603L` | (C++17) | Range-based `for` loop with different `begin`/`end` types |
| `__cpp_range_based_for` | `202211L` | (C++23) | Lifetime extension for all temporary objects in *range-initializer* |

### Keywords

`for`

### Example

```cpp
#include <iostream>
#include <vector>

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

    for (const int& i : v) // access by const reference
        std::cout << i << ' ';
    std::cout << '\n';

    for (auto i : v) // access by value, the type of i is int
        std::cout << i << ' ';
    std::cout << '\n';

    for (auto&& i : v) // access by forwarding reference, the type of i is int&
        std::cout << i << ' ';
    std::cout << '\n';

    const auto& cv = v;

    for (auto&& i : cv) // access by f-d reference, the type of i is const int&
        std::cout << i << ' ';
    std::cout << '\n';

    for (int n : {0, 1, 2, 3, 4, 5}) // the initializer may be a
                                     // braced-enclosed initializer list
        std::cout << n << ' ';
    std::cout << '\n';

    int a[] = {0, 1, 2, 3, 4, 5};
    for (int n : a) // the initializer may be an array
        std::cout << n << ' ';
    std::cout << '\n';

    for ([[maybe_unused]] int n : a)
        std::cout << 1 << ' '; // the loop variable need not be used
    std::cout << '\n';

    for (auto n = v.size(); auto i : v) // the init-statement (C++20)
        std::cout << --n + i << ' ';
    std::cout << '\n';

    for (typedef decltype(v)::value_type elem_t; elem_t i : v)
    // typedef declaration as init-statement (C++20)
        std::cout << i << ' ';
    std::cout << '\n';

    for (using elem_t = decltype(v)::value_type; elem_t i : v)
    // alias declaration as init-statement (C++23)
        std::cout << i << ' ';
    std::cout << '\n';
}
```

Output:

```text
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5
1 1 1 1 1 1
5 5 5 5 5 5
0 1 2 3 4 5
0 1 2 3 4 5
```

### Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

| DR | Applied to | Behavior as published | Correct behavior |
| --- | --- | --- | --- |
| CWG 1442 | C++11 | it was unspecified whether the lookup of non-member “`begin`” and “`end`” includes usual unqualified lookup | no usual unqualified lookup |
| CWG 2220 | C++11 | the names introduced in *init-statement* could be redeclared | the program is ill-formed in this case |
| CWG 2825 | C++11 | if *range-initializer* is a brace-enclosed initializer list, the non-member “`begin`” and “`end`” will be looked up | will lookup member “`begin`” and “`end`” in this case |
| P0962R1 | C++11 | member interpretation was used if either member “`begin`” and “`end`” is present | only used if both are present |

### See also

- [`for_each`](https://en.cppreference.com/w/cpp/algorithm/for_each): applies a function to a range of elements (function template)

## Podcast Host Debate & Socratic Standard Traps

Use the prompts and tricky ISO standard questions below to guide a Socratic audio discussion:

- Contrast raw storage duration with actual C++ object lifetime—and why malloc doesn't invoke constructors.
- Walk through why range-based for loops with temporary wrappers dangled for 12 years until C++23 P2718.
- Explain why strict aliasing breaks pointer-punning casts and how std::bit_cast solves it cleanly.

### Trap 1: [stmt.ranged] & P2718R0 (cppcon-stage)

Under C++17/C++20 rules, what happens in for (int x : make_holder().vec) if make_holder() returns a Holder by value?

```cpp
struct Holder { std::vector<int> vec{1, 2, 3}; };
Holder make_holder();
for (int x : make_holder().vec) { /* ... */ }
```

A. Safe in C++17 because the range-for __range reference extends Holder
B. Undefined behavior in C++17/C++20 because __range binds to .vec, leaving the Holder temporary to die before the loop body
C. Does not compile because vector cannot be copied
D. Extends Holder only when using auto&& x

**Standard Answer (B):** Undefined behavior in C++17/C++20 because __range binds to .vec, leaving the Holder temporary to die before the loop body

**Why:** In C++11–C++20, the range-for desugaring binds auto&& __range = make_holder().vec;. Because __range binds to the member subobject rather than the whole Holder temporary, the Holder temporary is destroyed at the semicolon of the __range declaration! C++23 (P2718R0) patched this rule specifically for range-for.

*CppCon speaker note:* One of the most famous real-world C++ bugs—even standard committee members tripped on it.

### Trap 2: [basic.life] & [ptr.launder] (standard-lawyer)

After destroying and placement-new constructing a struct containing a const int member in the same storage, how must you access the new object through the old pointer p?

```cpp
struct X { const int n; };
X* p = new X{1};
p->~X();
new (p) X{2};
```

A. p->n directly is always valid once placement new completes
B. std::launder(p)->n is required because X contains a const non-static data member
C. reinterpret_cast<X*>(p)->n avoids the requirement
D. Reusing storage containing a const member is impossible even with std::launder

**Standard Answer (B):** std::launder(p)->n is required because X contains a const non-static data member

**Why:** [basic.life]/8 states an old pointer automatically refers to the new object ONLY if the type has no const or reference non-static data members (among other rules). Otherwise, you must obtain the new pointer via placement new's return value or std::launder(p).

### Trap 3: [stmt.jump] & [class.dtor] (subtle)

In a single block { Guard a; Guard b; }, in what order are destructors invoked upon normal exit or an exception thrown after b is constructed?

A. a then b (construction order)
B. b then a (strict reverse order of construction)
C. Unspecified by the standard
D. Destructors are skipped if an exception unwinds

**Standard Answer (B):** b then a (strict reverse order of construction)

**Why:** Automatic local objects and class member subobjects are ALWAYS destroyed in exact reverse order of construction completion (LIFO), enabling dependent RAII guards like b holding a handle into a.

### Trap 4: [basic.lval] §7.2.1/11 & [bit.cast] (standard-lawyer)

Which method inspects the IEEE-754 bit pattern of a float as a uint32_t without violating C++ strict aliasing rules?

```cpp
float f = 3.14f;
```

A. uint32_t bits = *reinterpret_cast<uint32_t*>(&f);
B. union Pun { float f; uint32_t u; } p{f}; uint32_t bits = p.u;
C. auto bits = std::bit_cast<uint32_t>(f);
D. *(uint32_t*)(void*)&f

**Standard Answer (C):** auto bits = std::bit_cast<uint32_t>(f);

**Why:** Reading a float through a uint32_t* via reinterpret_cast violates strict aliasing ([basic.lval]), and reading an inactive union member is UB in C++ (unlike C99). C++20 std::bit_cast<uint32_t>(f) (or std::memcpy pre-C++20) is completely well-defined and constexpr.

---
Attribution: content from https://en.cppreference.com/w/cpp/language/range-for (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.