Range-for
Range-for walks a sequence without an index: for (auto& item : items). The compiler calls begin and end, binds the loop variable to each element, and stops when the iterators compare equal.
Detailed Explanation
The C-style loop over a vector is four places to get the bound wrong: the start, the test, the increment, and the subscript. Range-for, added in C++11, collapses that to "for each element of this sequence". You write the operation on the element. The compiler writes the iterator walk.
The desugaring is roughly:
{
auto&& range = items;
auto first = begin(range);
auto last = end(range);
for (; first != last; ++first) {
auto&& item = *first;
// your body
}
}
items can be a container, a raw array, a std::initializer_list, a std::span, or any type that provides begin/end as members or as ADL-found free functions. C++20 ranges (std::views::filter, std::views::transform) plug in because a view has begin and end.
The type of the loop variable decides copies versus aliases.
| Declaration | What you get |
|---|---|
auto x | A copy of each element. Safe. Expensive for std::string. |
auto& x | A mutable alias. Edits the container. Fails if the sequence yields temporaries. |
const auto& x | A read-only alias. The default for anything heavier than a machine word. |
auto&& x | A forwarding reference. Binds to lvalues and temporaries. Right for generic wrappers and for views that yield proxies. |
Use const auto& when you are reading a container of objects. Use auto& when you are rewriting fields. Use auto only for cheap types (int, enum, pointers) or when you want a snapshot that survives a later mutation of the container.
C++17 structured bindings combine with range-for: for (const auto& [key, value] : ages). That is the readable way to walk a std::map. The binding is into the value_type (std::pair<const Key, T>), so key is const.
Range-for does not give you the index. If you need it, walk with for (std::size_t i = 0; i < v.size(); ++i), use std::views::enumerate (C++23), or keep a counter beside a range-for. Do not convert to indices for speed on a vector; the generated code is the same pointer increment.
The sequence expression is bound once. for (auto& x : createList()) keeps the temporary createList() alive for the whole loop. That is why returning a container from a function and ranging over it is safe. Ranging over a function that returns a pointer into a temporary (for (auto& x : createList().items()) if items() returns a pointer or reference into the soon-to-die container) is a dangling-reference bug.
You cannot insert or erase elements in the container you are ranging over and expect the hidden iterators to stay valid. The same invalidation rules as a handwritten iterator loop apply. For std::vector, a push_back that reallocates invalidates the walk.
Code Examples
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> names{"ada", "al", "grace"};
for (const auto& name : names) {
std::cout << name << ' ';
}
std::cout << '\n'; // prints: ada al grace
for (auto& name : names) {
name.front() = static_cast<char>(std::toupper(name.front()));
}
std::cout << names[0] << '\n'; // prints: Ada
}#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> ages{{"ada", 36}, {"al", 46}};
for (const auto& [name, age] : ages) {
std::cout << name << '=' << age << '\n';
}
// prints:
// ada=36
// al=46
}Common Gotchas
Ranging over a temporary's inner reference
`for (auto x : loadUser().name)` is fine if `name` is a `std::string` returned by value. `for (auto c : loadUser().name)` where `name()` returns `const std::string&` into a temporary `User` dangles. Bind the user to a variable first.
`auto` copies
`for (auto line : lines)` copies every `std::string`. For a million lines that is a million allocations. Write `const auto&`.
The range is fixed at the start
changing which container the outer variable names does not retarget a loop that already bound `auto&& range = items`.