C++ Control Flow

Conditionals & Loops

Decision-making and iteration — if/else, switch, and every loop form including the clean range-based for.

C++20 ✓ Core Concepts 2 Topics
01

Conditionals & switch

C++ conditionals look like C's. switch works on integers and enums, and falls through without break — the same trap as C and old-style Java.

C++ — if, ternary & switch
int age = 20;

// if / else if / else
if (age >= 18) std::cout << "adult";
else std::cout << "minor";

// Ternary — compact if/else expression
std::string status = age >= 18 ? "adult" : "minor";

// if with initializer (C++17) — scope a variable to the if
if (int n = compute(); n > 0) {
    std::cout << n;   // n only exists inside this if
}

// switch — needs break, falls through without it
switch (day) {
    case 1: std::cout << "Mon"; break;
    case 3: std::cout << "Wed"; break;
    default: std::cout << "?";
}
A missing break in a switch silently continues into the next case. This "fall-through" is occasionally useful but far more often a bug — the compiler won't warn unless you ask it to.
02

Loops in C++

The range-based for (C++11) is the modern way to iterate any container. Use const auto& to avoid copying each element.

C++ — for, while, range-for
#include <vector>

// classic for — index-based
for (int i = 0; i < 5; i++) std::cout << i;   // 01234

// while
int n = 3;
while (n > 0) { std::cout << n; n--; }

// range-based for — iterate any container (C++11)
std::vector<int> nums = {3, 7, 2, 9};
int max = nums[0];
for (const auto& x : nums) {   // const auto& — no copy
    if (x > max) max = x;
}
std::cout << max;                // 9

// break / continue
for (int i = 0; i < 5; i++) {
    if (i == 2) continue;   // skip 2
    if (i == 4) break;      // stop at 4
    std::cout << i;             // 013
}
In a range-for, for (auto x : v) copies each element. Use const auto& to read without copying, or auto& when you need to modify elements in place.

Quick Quiz

1. A C++ switch without break will…
2. for (const auto& x : v) avoids…
3. To modify elements in place in a range-for, use…
4. if (int n = f(); n > 0) — the scope of n is…
5. do-while differs from while by…