Skip to content

Chapter 5 of 31

Control Flow

Build readable decisions with if, else, switch, guard clauses, and scoped initialization.

28 minutes 10 quick checksBy Subha Prasad
Lesson 5 of 31Course navigation

Lesson content

Read, practise, then check your understanding

if selects a branch from a condition convertible to bool. An else if chain tests top to bottom and executes only the first matching branch. Use braces even for one statement so later edits cannot silently change control flow.

std::string classify(int score) {
    if (score < 0 || score > 100) {
        return "invalid"; // guard clause
    }
    if (score >= 80) return "excellent";
    if (score >= 50) return "pass";
    return "retry";
}

Order overlapping conditions from most specific to least specific. Guard clauses keep exceptional paths short and reduce nesting.

switch for discrete values

enum class Command { start, pause, stop };

void run(Command command) {
    switch (command) {
        case Command::start: /* start */ break;
        case Command::pause: /* pause */ break;
        case Command::stop:  /* stop  */ break;
    }
}

switch accepts integral or enumeration conditions, not std::string. A missing break falls through; use [[fallthrough]] when that behavior is deliberate. A default can protect against unexpected input, but omitting it for an enum can let compilers warn about newly added enumerators.

C++17 permits an initializer before an if or switch condition, limiting a helper variable’s scope: if (auto it = map.find(key); it != map.end()). Prefer data-driven lookup or polymorphism when a decision tree grows large and changes frequently.

Knowledge check

Answer every question correctly to complete this chapter.

Which branch chain selects the first true condition?
Which values can label switch cases?
What prevents normal switch fallthrough?
Which C++17 feature can initialize a value in an if?
What attribute documents intended fallthrough?
What scalar condition value behaves as false?
Why order overlapping if branches carefully?
Can switch directly compare std::string case labels?
What is a useful role for an early return?
What should a default switch branch handle?

0 of 10 checks passed

Your progress is saved on this device.

Control Flow | C++ Lesson | Subha Prasad