Skip to content
Justice Tech School

Range based for

for (auto x : c) copies, for (auto& x : c) modifies and for (const auto& x : c) reads without copying.

Example
#include <iostream>
#include <vector>

int main() {
  std::vector<int> v = {1, 2, 3};
  for (auto &x : v) x *= 2;
  for (const auto &x : v) std::cout << x << " ";
  std::cout << "\n";
  return 0;
}

Result

2 4 6 

Exercise

No copy read only.

for ( auto &x : v)

Quiz Test

What does auto& allow?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.