C++ Range Based For Loop

The range-based for loop is a modern, clean way to visit every element in a collection such as an array or a vector. Instead of managing an index and worrying about going out of bounds, you just say, for each item in this collection, do something. It was introduced in C++11 and is now the go-to way to loop over data.

Looping over a collection

The syntax reads almost like English: for a declared variable, colon, then the collection. On each pass, the variable holds the next element from the collection until every element has been visited.

Looping through an array

#include <iostream>
using namespace std;

int main() {
  int numbers[] = {10, 20, 30, 40};
  for (int n : numbers) {
    cout << n << "\n";
  }
  return 0;
}

There is no index to manage and no length to calculate. The loop automatically handles every element from the first to the last, which removes a whole category of off-by-one mistakes.

Note: Use auto to let the compiler figure out the element type for you. Writing for (auto n : numbers) works the same and is handy when the type is long or complex.

Reading versus changing elements

If you only need to read the values, a plain copy like int n is fine. If you want to modify the elements in place, add an ampersand to make the variable a reference to the real element.

Doubling every value with a reference

#include <iostream>
using namespace std;

int main() {
  int prices[] = {5, 8, 12};
  for (int &p : prices) {
    p = p * 2;
  }
  for (int p : prices) {
    cout << p << "\n";
  }
  return 0;
}
  • for (int n : arr) makes a copy of each element, so changes do not affect the original.
  • for (int &n : arr) refers to the actual element, so changes stick.
  • for (auto n : arr) lets the compiler deduce the element type.
FormEffect on the collection
int n : arrRead only; each element is copied
int &n : arrCan modify the actual elements
const int &n : arrRead only, without copying

Choose the range-based for loop when you want to touch every element and you do not need the index. If you need the position number, a classic for loop with an index is still the right tool.