C++ Range-based for Loop
In this page:
Iterating Over Arrays
A range-based for loop iterates over every element of an array or container in sequence without you managing an index variable, eliminating an entire class of off-by-one bugs that come from writing i < size incorrectly in a traditional indexed loop.
Example: Iterating Over Arrays
#include <iostream>
int main() {
int arr[3] = {1, 2, 3};
for (int x : arr) std::cout << x << " ";
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using auto Keyword
Writing for (auto x : container) lets the compiler deduce each element's type automatically, which matters a lot when container holds a type that's tedious to spell out, like std::map<std::string, std::vector<int>>::value_type.
Example: Using auto Keyword
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3};
for (auto x : nums) std::cout << x << " ";
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Modifying Elements with References
By default, the loop variable is a copy of each element, so modifying it inside the loop body has no effect on the original container. Declaring the loop variable as a reference (auto&) binds it directly to each element in place, so changes you make are reflected in the container itself.
Example: Modifying Elements with References
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3};
for (auto &x : nums) x *= 2;
for (auto x : nums) std::cout << x << " ";
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Read-Only Access with const References
When you only need to read elements -- especially large ones, like strings or structs -- declaring the loop variable as const auto& avoids the cost of copying each element while also preventing accidental modification, which the compiler will flag as an error if you try.
Example: Read-Only Access with const References
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> words = {"hello", "world"};
for (const auto &w : words) std::cout << w << " ";
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Initializer Lists
You can range-for over a brace-enclosed initializer list directly, like for (int x : {1, 2, 3}), without first declaring a named array -- handy for quickly iterating a small, fixed set of values inline.
Example: Initializer Lists
#include <iostream>
int main() {
for (int x : {1, 2, 3}) std::cout << x << " ";
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: