How to Use Range Based For Loop in C++: Syntax and Examples
In C++, use the
range-based for loop to iterate over elements of a container or array easily with the syntax for (auto element : container). This loop automatically goes through each item without needing an index or iterator.Syntax
The range based for loop has this basic form:
for (declaration : container) {
// code using declaration
}declaration is a variable that represents each element in the container one by one.
container is any array, vector, or container you want to loop through.
This loop runs once for each element in the container.
cpp
for (auto element : container) { // use element }
Example
This example shows how to use a range based for loop to print all numbers in an array.
cpp
#include <iostream> int main() { int numbers[] = {10, 20, 30, 40, 50}; for (auto num : numbers) { std::cout << num << " "; } std::cout << std::endl; return 0; }
Output
10 20 30 40 50
Common Pitfalls
One common mistake is modifying elements inside the loop without using references, which only changes a copy, not the original element.
Wrong way (does not change original):
for (auto x : container) {
x = x + 1; // changes copy only
}Right way (use reference to modify original):
for (auto &x : container) {
x = x + 1; // changes original element
}Also, avoid using auto if you want to be explicit about the element type.
Quick Reference
Tips for using range based for loops:
- Use
autoto let the compiler infer the element type. - Use
&to get a reference if you want to modify elements. - Use
const auto &if you only want to read elements without copying. - Works with arrays, vectors, lists, and other containers supporting
begin()andend().
Key Takeaways
Use range based for loops to iterate easily over containers without manual indexing.
Use references in the loop variable to modify original elements.
Use const references to avoid copying when only reading elements.
Range based for loops work with arrays and standard containers like vector and list.
Avoid modifying loop variables without references as it only changes copies.