Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 171 Β· Control Flow

for Loops and Range-Based for

Learn C++ for loops - classic counting loops, range-based for by value, reference and const reference, loops with an initializer (C++20), views::enumerate and nested loops.

The while loop from the previous lesson can do any kind of repetition, but counting loops written with it spread their parts across several lines: the counter is declared above the loop, tested at the top and updated at the bottom. The for loop gathers all three on one line, so you can see at a glance where the loop starts, when it stops and how it moves.

C++ has two for loops. The classic for counts: from 0 to 9, from 100 down to 0 in steps of 5, over the indexes of a container. The range-based for (C++11) visits every element of a container, string, array or range, with no index at all. It's the loop you'll write most often in modern C++. In this lesson you'll learn both, the crucial difference between looping by value and by reference, the C++20 range-for with an initializer, C++23's std::views::enumerate for "index and element" loops, and nested loops.

The classic for loop

A for statement has three parts in its parentheses, separated by semicolons:

C++
for (init; condition; step) {
    body
}
  1. init runs once, before anything else. It usually declares the loop counter.
  2. condition is checked before every pass. If it's false, the loop ends.
  3. body runs.
  4. step runs after every pass, then it's back to the condition.

So for (int i = 0; i < 5; ++i) runs the body with i equal to 0, 1, 2, 3 and 4. It's the same as a while loop with the counter declared just before it, except that i exists only inside the loop.

C++ Counting loops

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The form for (int i = 0; i < n; ++i) is so common that experienced programmers read it as a single word: "repeat n times, with i from 0 to n βˆ’ 1". Prefer this half-open style (start included, end excluded) over i <= n - 1: it matches how indexes work in C++ (a container of size n has indexes 0 to n βˆ’ 1), and the number of passes is simply n - 0.

Whether you write ++i or i++ in the step makes no difference for an int. Many C++ programmers prefer ++i out of habit, because for complex iterator types the prefix form can avoid a copy (see Assignment and Increment Operators).

Variations

Every part is optional. Leave out the init if the variable already exists, leave out the step if the body updates the variable, and leave out the condition for an infinite loop: for (;;) runs until a break or return. The init can declare several variables of the same type, and the step can update several with the comma operator. A classic use is walking inward from both ends of a sequence:

C++ Two counters: reversing and checking palindromes

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

is_palindrome keeps right one past the character it compares, so it never computes size() - 1 on an empty string (which would wrap around to a huge unsigned number, as explained in Integer Types). The reversal loop above it is only safe because "stressed" isn't empty.

Index loops over containers

When you need the index while looping over a vector or string, compare against size() and use std::size_t for the counter so the types match (a signed int would trigger GCC's "comparison of integer expressions of different signedness" warning):

C++
std::vector<double> temps{18.5, 21.0, 19.25};
for (std::size_t i = 0; i < temps.size(); ++i) {
    std::println("day {}: {}", i + 1, temps[i]);
}

Counting down over unsigned indexes needs care: for (std::size_t i = v.size() - 1; i >= 0; --i) never ends, since an unsigned i is always >= 0, and it misbehaves on an empty vector too. GCC warns: "comparison of unsigned expression in '>= 0' is always true". Use for (std::size_t i = v.size(); i-- > 0; ), or better, a reverse view (shown below), or std::ssize(v) with a signed counter.

Range-based for

Most of the time you don't need an index at all; you need each element. The range-based for says exactly that:

C++
for (declaration : range) {
    body
}

It works with anything that has begin() and end(): every standard container, std::string, std::string_view, built-in arrays, braced lists like {1, 2, 3}, and ranges and views. There's no counter to get wrong and no way to run off the end.

By value, by reference or by const reference

The declaration decides how each element reaches the body, and the choice matters:

Declaration Each element is… Use it when…
auto x a copy elements are small (ints, chars, doubles) and you only read them
auto& x a reference to the element you want to modify the elements
const auto& x a read-only reference elements are large (strings, structs) and you only read them
C++ Copies, references and const references

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first loop is a classic bug: it looks like it adds 5 to every score, but it modifies copies that vanish at the end of each pass. When a loop is supposed to change elements, the declaration must be a reference.

For read-only loops, the rule of thumb is: auto for cheap types like int and char, const auto& for everything else. Copying each std::string in a loop over thousands of names allocates memory on every pass for no reason.

Many kinds of ranges

C++ Arrays, maps and braced lists

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

const auto& [city, people] is a structured binding (C++17): each map element is a std::pair, and the binding gives its two halves names. A std::map keeps keys sorted, so the cities print alphabetically. Maps get their own lesson in std::map.

Index and element together: views::enumerate (C++23)

Sometimes you need both the element and its position. C++23's std::views::enumerate (header <ranges>) pairs each element with its index, and C++20's std::views::iota and std::views::reverse cover other counting needs without a hand-written index loop:

C++ enumerate, iota and reverse

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

enumerate gives you the index as a signed integer and the element as a reference into the container, so the last loop really changes podium[0]. std::views::enumerate needs GCC 13+ or a recent MSVC; Clang's libc++ only gained it in version 23. Views are covered in depth in Ranges and Views.

Range-based for with an initializer (C++20)

Like if and switch, a range-based for can start with an init statement whose variables live only for the loop. It's handy for a counter or for keeping a temporary container alive:

C++
for (int line = 1; const auto& name : names) {
    std::println("{}: {}", line++, name);
}

for (auto words = load_words(); const auto& w : words) {   // words lives for the loop
    std::println("{}", w);
}

Lifetime of the range

The range expression is evaluated once, before the first pass. If it creates a temporary object and you loop over a reference into it, older C++ destroyed the temporary before the loop body ran:

C++
for (int x : make_report().values()) { ... }   // values() returns a reference into the report

Before C++23 this was a dangling-reference bug: the report died at the start of the loop. C++23 extends the lifetime of every temporary in the range expression to the end of the loop, and GCC 15 implements it in -std=c++23 mode, so this code is fine on our server. Older compilers and standards don't have the fix, so in shared code it's still wise to store the object in a variable (or use the initializer form above) first.

Don't add or remove elements while a range-for runs over a container. push_back on a std::vector may reallocate its storage, which invalidates the iterators the loop uses behind the scenes, and that's undefined behavior. Collect changes in a second container and apply them after the loop, or use algorithms like std::erase_if (see Iterators).

Nested loops

A loop inside a loop runs the inner loop completely for every pass of the outer one. With an outer loop of r passes and an inner loop of c passes, the inner body runs r Γ— c times. That's the natural shape for grids, tables and pairs of elements:

C++ Tables, patterns and pairs

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Starting the inner loop at i + 1 visits each unordered pair exactly once and never pairs an element with itself. Keep in mind that nested loops multiply work: two nested loops over 100,000 elements run 10 billion times. If you need to stop both loops as soon as you find something, see break, continue and goto.

Which for loop?

You need… Write
each element, read-only for (const auto& x : c) (or auto x for small types)
each element, to modify for (auto& x : c)
index and element for (auto [i, x] : std::views::enumerate(c))
numbers from a to b for (int i = a; i < b; ++i) or std::views::iota(a, b)
a step other than 1, or two counters classic for
backwards `c
key and value of a map for (const auto& [key, value] : m)

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. How many times does for (int i = 2; i < 10; i += 2) run its body?

    i takes the values 2, 4, 6 and 8. When it becomes 10, the condition i < 10 is false, so the body runs 4 times.
  2. 2. std::vector<int> v{1, 2, 3}; for (auto x : v) { x *= 10; } What does v contain afterwards?

    auto x makes a copy of each element, so the multiplication changes only the copy. Use auto& x to modify the vector.
  3. 3. Which declaration is best for reading every element of a std::vector<std::string> without modifying it?

    const auto& avoids copying each string and prevents accidental modification. The first two copy every string; auto& allows changes you don't intend.
  4. 4. Why does for (std::size_t i = v.size() - 1; i >= 0; --i) never end?

    Unsigned values can't be negative, so the condition never fails. Use a reverse view, std::ssize with a signed counter, or the pattern for (std::size_t i = v.size(); i-- > 0; ).
  5. 5. How many lines does this print? for (int r = 0; r < 3; ++r) for (int c = 0; c < 4; ++c) std::println("x");

    The inner loop runs completely (4 times) for each of the 3 outer passes, so the body runs 3 Γ— 4 = 12 times.

Summary

  • The classic for (init; condition; step) keeps a counting loop on one line; its variables exist only inside the loop. Prefer half-open ranges: for (int i = 0; i < n; ++i).
  • Init can declare several variables and the step can update several with commas; for (;;) loops forever.
  • Use std::size_t for indexes compared with size(), and never count down an unsigned with i >= 0.
  • Range-based for (x : range) visits every element of containers, strings, arrays, braced lists and views.
  • auto x copies, auto& x modifies, const auto& x reads large elements without copying.
  • std::views::enumerate (C++23), iota and reverse replace most hand-written index loops; C++20 lets a range-for start with an initializer.
  • Don't change a container's size while looping over it; nested loops multiply the work.

Next: break, continue and goto, where you'll learn to leave loops early and skip passes.