C++'s if, switch, for, and while work exactly as in C, plus a modern addition that eliminates a whole class of indexing bugs.
std::vector<int> nums = {10, 20, 30, 40};
// C-style loop — still works, but verbose and error-prone
for (size_t i = 0; i < nums.size(); i++) {
std::cout << nums[i] << " ";
}
// Range-based for loop (C++11) — the modern default
for (int n : nums) {
std::cout << n << " ";
}
// Modify elements in place using a reference
for (int &n : nums) {
n *= 2;
}
The range-based for loop (C++11) iterates directly over a container's elements without manual indexing — no off-by-one errors, no need to call .size(), and it works uniformly across arrays, std::vector, std::string, std::map, and any other type that provides begin()/end(). Writing for (int n : nums) copies each element into n; writing for (int &n : nums) binds n as a reference to the actual element, letting the loop body modify the original container in place — a distinction worth being deliberate about, especially for large elements where copying is wasteful.
if, switch, while, and do...while carry over from C unchanged in their basic form. C++17 added an extra convenience to if and switch — an initializer statement, if (auto it = m.find(key); it != m.end()) { ... } — that scopes a helper variable to just the condition and its body, keeping it out of the surrounding scope once the block ends.