C++'s if, while, do-while, and classic for loops use the same syntax C does. The range-based for loop, added in C++11, iterates directly over any container (an array, a vector, a string) without manual index management, working with any type that provides begin()/end() iterators — which includes every standard container and is straightforward to add to custom types too. C++17 additionally allows if and switch statements to include an init-statement, scoping a helper variable to just that conditional block rather than leaking into the surrounding scope.
The classic, C-style for loop
This still works exactly as in C, and remains the right choice when the loop needs the index itself, not just each element.
std::vector<int> numbers = {10, 20, 30, 40};
for (int i = 0; i < numbers.size(); i++) {
std::cout << numbers[i] << " ";
}Range-based for: no manual indexing at all (C++11+)
This iterates every element directly, with no index variable, no bounds to get wrong, and no off-by-one risk — auto& avoids copying each element, useful for larger element types.
std::vector<int> numbers = {10, 20, 30, 40};
for (auto n : numbers) { // copies each element
std::cout << n << " ";
}
for (auto& n : numbers) { // reference — no copy, and can modify in place
n *= 2;
}if with an init-statement (C++17+)
result is scoped to ONLY the if/else block — it doesn't leak into the surrounding function, avoiding a common source of accidental name reuse in longer functions.
std::map<std::string, int> ages = {{"Alice", 30}};
if (auto it = ages.find("Alice"); it != ages.end()) {
std::cout << it->second << "\n"; // it is scoped to just this if/else
}
// it is NOT accessible here — it went out of scope with the if statement