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.
0 of 10 checks passed
Your progress is saved on this device.