Range-based For Loop

Range-based For Loop in C++: Iterate over everything in a container without ever writing an index.

Iterate over everything in a container without ever writing an index.

The Analogy: Handing Out Programmes at the Door

The old way of visiting every seat in a theatre is to count: seat 0, seat 1, seat 2 … stop before you pass the last row. It works, but every part of it is your responsibility — where to start, when to stop, whether < or <= is right, and whether the seat number you just wrote actually exists. Get one of those wrong and you walk into a wall.

The range-based for is standing at the door and handing a programme to each person as they come in. You never think about numbers at all. There is no "one past the last person" to trip over, no off-by-one, and no way to accidentally hand a programme to somebody who is not there. You simply say "for each attendee" and describe what to do with them.

The one thing you must decide is whether you are handing them a programme (reading a copy), writing on the programme they already hold (a reference), or promising not to touch it (a const reference). That single choice is the whole of the syntax that matters.


Syntax or Core Structure

The shape is for (declaration : range) { body }:

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <array>

int main() {
    // 1. A plain array. The compiler knows its length; you do not restate it.
    int scores[] = {90, 75, 88};
    for (int s : scores) std::cout << s << " ";
    std::cout << "\n";

    // 2. A vector, reading only. const auto& is the everyday default.
    std::vector<std::string> names{"Ada", "Grace", "Alan"};
    for (const auto& name : names) std::cout << name << " ";
    std::cout << "\n";

    // 3. auto& when you intend to modify the elements in place.
    std::vector<int> values{1, 2, 3};
    for (auto& v : values) v *= 10;
    for (const auto& v : values) std::cout << v << " ";
    std::cout << "\n";

    // 4. Plain auto takes a copy: changes are thrown away.
    for (auto v : values) v = 0;
    std::cout << "still " << values[0] << "\n";

    // 5. A string iterates its characters.
    for (const char c : std::string("hi!")) std::cout << c << ".";
    std::cout << "\n";

    // 6. A map yields pairs; structured bindings name the halves (C++17).
    std::map<std::string, int> stock{{"bolt", 12}, {"nut", 40}};
    for (const auto& [item, count] : stock)
        std::cout << item << "=" << count << " ";
    std::cout << "\n";

    // 7. Modifying a map's values, but never its keys.
    for (auto& [item, count] : stock) count += 1;
    std::cout << "bolts now " << stock["bolt"] << "\n";

    // 8. A braced list is itself a range.
    for (const int day : {1, 7, 30}) std::cout << day << "d ";
    std::cout << "\n";

    // 9. Nested ranges: a grid, read then written.
    std::vector<std::vector<int>> grid{{1, 2}, {3, 4}};
    for (auto& row : grid)
        for (auto& cell : row)
            cell += 100;
    for (const auto& row : grid) {
        for (const int cell : row) std::cout << cell << " ";
        std::cout << "\n";
    }

    // 10. std::array behaves the same, and knows its own size.
    std::array<double, 3> temps{18.5, 21.0, 19.25};
    double sum = 0.0;
    for (const double t : temps) sum += t;
    std::cout << "mean " << sum / temps.size() << "\n";

    return 0;
}

Output:

90 75 88
Ada Grace Alan
10 20 30
still 10
h.i.!.
bolt=12 nut=40
bolts now 13
1d 7d 30d
101 102
103 104
mean 19.5

Cases 3 and 4 are the pair to remember: auto& wrote through to the vector, plain auto modified a copy that was discarded at the end of each iteration. Case 5 shows that const char c is perfectly reasonable for a cheap type — you are not obliged to use auto at all. And case 7 is worth noting: you may modify a map's values through auto&, but the key half of the binding is const, because changing a key in place would break the map's ordering.


Technical Depth: What the Compiler Rewrites It Into

The desugaring

A range-based for is not a new kind of loop. The compiler expands it into an ordinary iterator loop:

for (const auto& x : container) { body }

// becomes, roughly:
{
    auto&& range = container;              // the range is bound ONCE
    auto first = range.begin();
    auto last  = range.end();
    for (; first != last; ++first) {
        const auto& x = *first;
        body
    }
}

Everything about the loop follows from that expansion:

  • begin() and end() are called once, before the first iteration. Anything that invalidates those iterators mid-loop is undefined behaviour.
  • The loop variable is initialised from *first each time round, which is why plain auto copies.
  • There is no index anywhere, so there is nothing to get wrong — and nothing to read either.
  • It is exactly as fast as the hand-written index loop. The abstraction costs nothing at runtime.

What counts as a range

Anything with begin() and end() works — member functions, or free functions found by argument-dependent lookup. That covers every standard container, std::string, std::array, C arrays of known size, std::initializer_list, and any class of your own that provides the pair:

class Deck {
    std::vector<int> cards;
public:
    auto begin() { return cards.begin(); }
    auto end()   { return cards.end(); }
    auto begin() const { return cards.begin(); }    // needed for const Deck
    auto end()   const { return cards.end(); }
};

Deck deck;
for (const int card : deck) { }                     // just works

A raw pointer is not a range: int* p = new int[10]; has no length, so for (int x : p) will not compile. That is one of the quiet arguments for std::vector and std::array.

Choosing the declaration

WrittenMeaningUse for
for (auto x : c)A copy per iterationCheap types: int, char, double, pointers
for (const auto& x : c)Read-only referenceThe default for anything non-trivial
for (auto& x : c)Modifiable referenceWhen you write to the elements
for (auto&& x : c)Forwarding referenceProxy elements and generic code
for (const T& x : c)Same, type spelled outWhen the element type is the useful information

The mistake that costs real performance is for (auto row : bigTable) — a full copy of every row, every iteration, invisible on the line that causes it.

There is no index, and that is sometimes the problem

The range-based for deliberately hides the position. When you need it, you have three honest options:

// 1. Keep your own counter.
std::size_t i = 0;
for (const auto& name : names) { std::cout << i++ << ": " << name << "\n"; }

// 2. Go back to an index loop -- correct, not a defeat.
for (std::size_t j = 0; j < names.size(); ++j)
    std::cout << j << ": " << names[j] << "\n";

// 3. C++20 ranges, when you have them.
// for (auto [k, name] : names | std::views::enumerate)  // C++23

Needing the index at all is a signal. If you are using it to reach a neighbouring element (v[i - 1], v[i + 1]), the index loop is the right tool and the range-based for is the wrong one.

Do not change the container's shape while looping

std::vector<int> v{1, 2, 3, 4};

for (const int x : v) {
    if (x == 2) v.push_back(99);       // UB: push_back may reallocate
}

for (const int x : v) {
    if (x == 2) v.erase(v.begin());    // UB: iterators invalidated
}

Both compile and may even appear to work. begin() and end() were captured before the first iteration, so a reallocation leaves the loop walking freed memory. To remove elements, use the erase-remove idiom (or C++20's std::erase_if) instead; to add them, collect into a second container and append afterwards.

Modifying element values is always fine — that is what auto& is for. It is only insertion and removal that break the loop.

The dangling-range trap

std::vector<int> makeData();

for (const int x : makeData()) { }                  // fine: the temporary is kept alive

for (const int x : makeData().front()) { }          // wrong idea, and worse:
// for (const auto& c : getUser().name()) { }       // DANGLING before C++23

The range expression itself is lifetime-extended, but a sub-object of a temporary is not. Iterating something().member() where something() returns by value reads destroyed memory. C++20's init-statement form gives you the fix:

for (auto user = getUser(); const auto& c : user.name()) { }   // C++20

std::vector<bool> needs auto&&

std::vector<bool> stores bits and hands back a proxy object rather than a real bool&:

std::vector<bool> flags{true, false, true};

// for (bool& f : flags) f = false;      // ERROR: no bool& exists
for (auto&& f : flags) f = false;        // works: binds the proxy

This is the main reason auto&& exists in loops, and a good reason to prefer std::vector<char> or std::bitset when you want a mutable array of flags.

C++20 ranges make it composable

#include <ranges>

for (const int n : values | std::views::filter([](int n) { return n % 2 == 0; })
                          | std::views::transform([](int n) { return n * n; }))
    std::cout << n << " ";

for (const auto& name : names | std::views::reverse) std::cout << name << " ";
for (const int n : std::views::iota(1, 6)) std::cout << n << " ";     // 1..5

Views are lazy — nothing is copied, and no intermediate container is built. Before C++20, reverse iteration needed std::rbegin/rend and an explicit iterator loop.

When to reach for something else

NeedBetter tool
Every element, in orderRange-based for
The index, or a neighbourIndex loop
Two containers in parallelIndex loop, or std::transform with two ranges
Remove while iteratingstd::erase_if, or the erase-remove idiom
Only part of a containerIterator loop, or std::views::take / drop
Reverse orderstd::views::reverse (C++20), else rbegin/rend

Real World Example: A Cinema Seat Map

A seat map is a grid of characters — . free, # sold, H held. Most of the work is "visit every seat", which is exactly what the range-based for is for. One job is not, and the contrast is the point of the example.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <optional>
#include <algorithm>
#include <iterator>

using SeatMap = std::vector<std::string>;

void render(const SeatMap& hall) {
    std::cout << "   0123456789\n";
    char label = 'A';
    for (const auto& row : hall) {            // const auto& -- rows are strings
        std::cout << label << "  " << row << "\n";
        ++label;                              // our own counter, since there is no index
    }
}

std::map<char, int> tally(const SeatMap& hall) {
    std::map<char, int> counts;
    for (const auto& row : hall)
        for (const char seat : row)           // char is cheap: a copy is right
            ++counts[seat];
    return counts;
}

int expireHolds(SeatMap& hall) {
    int released = 0;
    for (auto& row : hall)                    // auto& -- we are going to write
        for (char& seat : row) {              // char& -- the element itself
            if (seat == 'H') { seat = '.'; ++released; }
        }
    return released;
}

int freeSeats(const std::string& row) {
    return static_cast<int>(std::count(row.begin(), row.end(), '.'));
}

// Adjacency needs positions, so this one is an index loop on purpose.
std::optional<std::size_t> findRun(const std::string& row, std::size_t n) {
    std::size_t run = 0;
    for (std::size_t i = 0; i < row.size(); ++i) {
        run = (row[i] == '.') ? run + 1 : 0;
        if (run == n) return i + 1 - n;
    }
    return std::nullopt;
}

int main() {
    SeatMap hall{
        "..##..H...",
        "###...##..",
        "..H..H....",
        "#########.",
    };

    render(hall);
    std::cout << "\n";

    for (const auto& [symbol, count] : tally(hall))
        std::cout << "  '" << symbol << "' " << count << "\n";
    std::cout << "\n";

    std::cout << "expired holds: " << expireHolds(hall) << "\n\n";
    render(hall);
    std::cout << "\n";

    char label = 'A';
    for (const auto& row : hall) {
        std::cout << label << ": " << freeSeats(row) << " free";
        if (auto start = findRun(row, 3))
            std::cout << ", 3 together from seat " << *start;
        else
            std::cout << ", no run of 3";
        std::cout << "\n";
        ++label;
    }
    std::cout << "\n";

    auto best = std::max_element(hall.begin(), hall.end(),
        [](const std::string& a, const std::string& b) {
            return freeSeats(a) < freeSeats(b);
        });
    std::cout << "emptiest row: "
              << static_cast<char>('A' + std::distance(hall.begin(), best)) << "\n";

    return 0;
}

Output:

   0123456789
A  ..##..H...
B  ###...##..
C  ..H..H....
D  #########.

  '#' 16
  '.' 21
  'H' 3

expired holds: 3

   0123456789
A  ..##......
B  ###...##..
C  ..........
D  #########.

A: 8 free, 3 together from seat 4
B: 5 free, 3 together from seat 3
C: 10 free, 3 together from seat 0
D: 1 free, no run of 3

emptiest row: C

Look at what each loop declares. tally reads and never writes, so the outer loop is const auto& — the rows are std::strings and copying four of them per call would be pure waste — while the inner loop is const char, because a character is a single byte and taking a reference to it would be more machinery than the thing it refers to. That is the general rule made concrete: reference for anything you would not happily pass by value.

expireHolds is the mirror image. The outer loop must be auto& or the inner loop would be writing into a copy of the row that is discarded at the end of the iteration — and, tellingly, the program would still compile and still report "expired holds: 3" while changing nothing in hall. That is the kind of bug that only the second render call catches. The inner char& seat writes straight into the string's storage. Note that expireHolds changes element values only; it never inserts or erases, so the loop is entirely safe.

findRun is the honest exception. It has to know whether three free seats are next to each other, which means comparing positions, and a range-based for deliberately throws positions away. Trying to force it — by carrying a manual index alongside, or by keeping a "previous character" variable — would produce something longer and harder to read than the index loop it was avoiding. The rule worth taking from this: the range-based for is for "each element, independently". The moment an element's neighbours or coordinates matter, an index loop is the clearer tool, not a failure to modernise.

The two places that do need a position but only a cosmetic one — the row labels in render and in main's summary — use a plain char label counter advanced by hand. That is perfectly idiomatic. The label is not being used to access the container, only to name what was found, so the loop keeps its simple form and the counter stays a detail.

Finally, std::max_element with a lambda replaces what would otherwise be a loop with a "best so far" variable, and std::distance(hall.begin(), best) converts the returned iterator back into the row letter. Reaching for the algorithm rather than any kind of loop is often the last step of this progression: index loop, then range-based for, then no loop at all.


Common Mistakes

  1. for (auto row : table) when row is a std::string or std::vector. This copies every element. Write const auto&.
  2. Expecting plain auto to write through. for (auto v : values) v *= 2; compiles, runs, and changes nothing. Use auto&.
  3. Inserting or erasing inside the loop. push_back or erase invalidates the iterators the loop captured before it started. Use std::erase_if, or build a second container.
  4. Iterating a pointer. int* p = new int[n]; has no begin()/end(), so it is not a range. Use std::vector.
  5. Iterating a sub-object of a temporary. for (auto& c : getUser().name()) dangles before C++23. Bind the temporary first, or use the C++20 init-statement form.
  6. for (bool& f : flags) on a std::vector<bool>. There is no real bool&; use auto&&.
  7. Forgetting const overloads of begin/end on your own class, so it works for Deck but not const Deck.
  8. Forcing it when you need an index. If the body uses v[i - 1], an index loop is the correct choice.

Best Practices

  • Default to const auto&; use auto& to modify; use plain auto (or the spelled-out type) only for cheap values.
  • Prefer the range-based for over an index loop whenever the body treats each element independently.
  • Use structured bindings for maps: for (const auto& [key, value] : m).
  • Give your own containers begin()/end() in both const and non-const forms, and the loop comes free.
  • Never insert into or erase from the container you are iterating.
  • Reach for a standard algorithm before writing a loop with an accumulator or a "best so far" variable.
  • With C++20, use std::views::reverse, filter and transform instead of hand-rolled iterator loops.
  • Use an index loop without embarrassment when positions or neighbours matter.

Practice Exercises

  1. Write normaliseNames(std::vector<std::string>& names) that upper-cases the first letter of each name in place. Then write a deliberately broken version using plain auto, run both, and record why the broken one reports success while changing nothing.
  2. Given std::map<std::string, std::vector<int>> scores, print every student with their total and their best score using structured bindings, then add ten points to every score using auto&. Explain why the key half of the binding cannot be modified.
  3. Add bookRun(SeatMap& hall, char row, std::size_t n) to the seat-map program: use findRun to locate n adjacent free seats in that row, mark them #, and return whether it succeeded. Then write refundRow that removes fully sold rows from the map — and explain why that one cannot use a range-based for.