← Back to C++ Course | Chapter 16: Modern C++ | Lesson 2 of 9

C++ Range-based for Loop

A range-based for loop goes through every item in a collection without you counting, like handing a sticker to each child in a line. It is shorter and safer than counting.
Syntax
cpp
for (data_type element : container) {
  // use element
}

for (auto &element : container) {
  // modify element
}

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

cpp
// Include std::cout and std::cin
#include <iostream>

// Program execution starts in main()
int main() {
	int arr[3] = {1, 2, 3};
	for (int x : arr) std::cout << x << " ";
	// Print to the console with cout
	std::cout << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

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

cpp
// Include std::cout and std::cin
#include <iostream>
// Include std::vector
#include <vector>

// Program execution starts in main()
int main() {
	// Create a vector named nums (a resizable array)
	std::vector<int> nums = {1, 2, 3};
	// Range-based for loop: visit every element of nums
	for (auto x : nums) std::cout << x << " ";
	// Print to the console with cout
	std::cout << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

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

cpp
// Include std::cout and std::cin
#include <iostream>
// Include std::vector
#include <vector>

// Program execution starts in main()
int main() {
	// Create a vector named nums (a resizable array)
	std::vector<int> nums = {1, 2, 3};
	// Range-based for loop: visit every element of nums
	for (auto &x : nums) x *= 2;
	// Range-based for loop: visit every element of nums
	for (auto x : nums) std::cout << x << " ";
	// Print to the console with cout
	std::cout << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

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

cpp
// Include std::cout and std::cin
#include <iostream>
// Include std::vector
#include <vector>
#include <string>

// Program execution starts in main()
int main() {
	// Create a vector named words (a resizable array)
	std::vector<std::string> words = {"hello", "world"};
	// Range-based for loop: visit every element of words
	for (const auto &w : words) std::cout << w << " ";
	// Print to the console with cout
	std::cout << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

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

cpp
// Include std::cout and std::cin
#include <iostream>

// Program execution starts in main()
int main() {
	for (int x : {1, 2, 3}) std::cout << x << " ";
	// Print to the console with cout
	std::cout << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting & in for (auto x : v) and modifying only a copy.
  2. Adding or removing elements of the container inside the loop.
  3. Forgetting const when the loop only reads elements.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.