`for` — C++ Keyword
`for` — C++ Keyword
The for keyword in C++: traditional counted loop and range-based for loop.
`for` — C++ Keyword
The for keyword in C++: traditional counted loop and range-based for loop.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
forExecutes a body repeatedly. C++ provides both the traditional three-part for loop and the range-based for loop (C++11).
// Traditional
for (init-statement; condition; iteration-expression) statement
// Range-based (C++11)
for (range-declaration : range-expression) statement
// Range-based with initializer (C++20)
for (init-statement; range-declaration : range-expression) statement
#include <print>
#include <vector>
int main() {
// Traditional counted loop
for (int i = 0; i < 5; ++i) {
std::print("{} ", i); // 0 1 2 3 4
}
std::println();
// Range-based for loop
std::vector<int> v = {10, 20, 30};
for (int x : v) {
std::print("{} ", x); // 10 20 30
}
std::println();
// Range-based with initializer (C++20)
for (auto& data = v; int x : data) {
std::print("{} ", x);
}
}
for may be omitted; for (;;) is an infinite loop.for when iterating over a whole container.const auto& to avoid copies when the element type is heavy.forforint main() {
// Pick one facility from this reference page.
// Write the smallest program that exercises its main precondition,
// complexity rule, or lifetime constraint before scaling up.
return 0;
}