Module 2 · Variables, Operators and Control Flow — topic 3 of 4
Control Flow: if, else and switch
Decisions with if/else ladders, if with an initialiser (C++17), the switch statement with fall-through and [[fallthrough]], and the conditional operator.
Learning objectives
- Write if/else ladders and nested conditions
- Use switch with break, default and [[fallthrough]]
- Use C++17 if-with-initialiser to limit variable scope
Definition
Selection statements choose which statements execute:ifruns a branch when its condition converts to true;switchjumps to thecaselabel equal to an integral or enumeration value.
Introduction
C++ decision statements look like C's, but conditions are bool, and modern C++ adds features that keep variables in the smallest possible scope.
Any expression that converts to bool can be a condition: numbers (zero is false), pointers (null is false) and objects such as streams, which become false after a failed read. That is why if (std::cin >> x) and if (ptr) are idiomatic C++.
Choosing between if and switch is mostly about the shape of the decision: ranges and combinations of conditions call for if, while one integer or enum compared against many fixed values reads more clearly as a switch and can compile to a jump table.
Why it matters
Correct conditions are central to every program; boundary bugs (> vs >=) are among the most common errors.
Limiting variable scope reduces accidental reuse of stale values.
Detailed explanation
An else-if ladder runs the first branch whose condition is true; order thresholds from most to least specific.
switch works on integers, characters and enums (not strings). Each case should end with break; mark intentional fall-through with [[fallthrough]]; (C++17).
if with initialiser: if (auto it = m.find(k); it != m.end()) { ... } declares it only for the if/else statements.
Always use braces for bodies; an else binds to the nearest if.
Syntax
- Case labels must be constant expressions.
defaulthandles unmatched values.- Use
[[fallthrough]]to document intent.
Code examples
Grade ladder
95:O 75:A 74:B 40:P 12:F
switch on a char
42
More examples
if with initialiser and [[fallthrough]]
pen: 40 left book: out of stock bag: not sold here perks: 30
Step-by-step explanation
itexists only within the if/else chain.findreturnsend()when the key is missing.it->secondis the stored quantity.- Level 2 enters at case 2 and deliberately falls into case 1: 20 + 10 = 30.
Expected output
Running “if with initialiser and [[fallthrough]]” prints exactly:
Practical applications
- Menu-driven applications switch on the user's choice.
- Lookup-then-act code uses if-with-initialiser.
- Tiered pricing uses deliberate fall-through.
Best practices
- Use braces for every branch.
- Include
defaultin every switch. - Keep variables in the narrowest scope (if-initialisers help).
Common mistakes
Missing break
Avoid
Prefer
Without break, choosing 1 also quits.
Switching on a string
Avoid
Prefer
switch needs an integral or enum type; compare strings with ==.
Important notes
- Compilers warn about unmarked fall-through with
-Wimplicit-fallthrough. - C++20 adds
[[likely]]and[[unlikely]]hints for branches.
Key takeaways
- Else-if ladders stop at the first true condition.
- switch needs break; mark intentional fall-through.
if (init; cond)limits scope.
Try it yourself
- 1Write a program that reads a year and prints whether it is a leap year.
- 2Write a switch-based menu with an
enum class Choice.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
6 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhat is printed?
- BeginnerCan a C++ `switch` statement switch on a std::string?