liveBook · Manning

Range-based for loop

As explained in 100 C++ Mistakes and How to Avoid Them

A range-based for loop is a C++ iteration statement that traverses the elements of a range or container without explicit index management.

Overusing index-based loops makes iteration longer, harder to read, and vulnerable to off-by-one errors. A range-based for loop focuses on each element instead of loop mechanics. section 2.6

Read the colon as “in”: each element is assigned to the loop variable in sequence. By default, that variable is a copy, so changes do not affect the container and class elements may be copied expensively. Prefer a const reference for read-only class elements, or a non-const reference when modification is required. section 2.6

Listing 2.11 Using index values to iterate over a container
template <typename T>
T sum(const std::vector<T>& values) {
    T sum = (T)0;
    for (int i = 0; i < values.size(); ++i)                 #1
        sum += values[i];
    return sum;
}
 
int main() {
    std::vector<int> values;
    for (int i = 0; i < 10; ++i)
        values.push_back(10*i + i);                         #2
    std::cout << sum(values) << '\n';
    return 0;
}

Compare indexed traversal with a range-based sum function using const references. section 2.6

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains syntax, sequencing, copies, references, and const choices through a container-summing example.
Examples
Contrasts a vector sum using indexes with one using a const reference in a range-based loop.
What it assumes
Assumes familiarity with containers and traditional for-loop traversal while explaining the modern alternative directly.
What you can do after
Apply range-based for loops to traverse containers and select value, const-reference, or reference semantics appropriately.
How it connects
Connects containers, index-based loops, references, const correctness, and copy constructors.

Also explained in

Compare how 2 books explain range-based for loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.