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

C++ Range-based for Loop

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 <iostream>

int main() {
	int arr[3] = {1, 2, 3};
	for (int x : arr) std::cout << x << " ";
	std::cout << std::endl;
	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 <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;
}

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 <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;
}

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 <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;
}

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 <iostream>

int main() {
	for (int x : {1, 2, 3}) std::cout << x << " ";
	std::cout << std::endl;
	return 0;
}

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.