Skip to content

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.

Beginner 13 min read·Lesson 6 of 40 in C++ Programming

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: if runs a branch when its condition converts to true; switch jumps to the case label 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

C++
if (marks >= 90) { grade = 'O'; }
else if (marks >= 75) { grade = 'A'; }
else { grade = 'B'; }
switch (choice) {
case 1: add(); break;
case 2: [[fallthrough]];
case 3: list(); break;
default: std::cout << "?";
}
  • Case labels must be constant expressions.
  • default handles unmatched values.
  • Use [[fallthrough]] to document intent.

Code examples

Grade ladder

C++
#include <iostream>
char grade(int m) {
if (m >= 90) return 'O';
else if (m >= 75) return 'A';
else if (m >= 60) return 'B';
else if (m >= 40) return 'P';
return 'F';
}
int main() {
for (int m : {95, 75, 74, 40, 12}) std::cout << m << ':' << grade(m) << ' ';
std::cout << '\n';
return 0;
}
Output
95:O 75:A 74:B 40:P 12:F

switch on a char

C++
#include <iostream>
int main() {
char op = '*';
int a = 6, b = 7;
switch (op) {
case '+': std::cout << a + b; break;
case '*': std::cout << a * b; break;
default: std::cout << "unknown";
}
std::cout << '\n';
return 0;
}
Output
42

More examples

if with initialiser and [[fallthrough]]

C++
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> stock{{"pen", 40}, {"book", 0}};
for (std::string item : {"pen", "book", "bag"}) {
if (auto it = stock.find(item); it == stock.end())
std::cout << item << ": not sold here\n";
else if (it->second == 0)
std::cout << item << ": out of stock\n";
else
std::cout << item << ": " << it->second << " left\n";
}
int level = 2, perks = 0;
switch (level) {
case 3: perks += 30; [[fallthrough]];
case 2: perks += 20; [[fallthrough]];
case 1: perks += 10; break;
default: perks = 0;
}
std::cout << "perks: " << perks << '\n';
return 0;
}
Output
pen: 40 left
book: out of stock
bag: not sold here
perks: 30

Step-by-step explanation

  • it exists only within the if/else chain.
  • find returns end() when the key is missing.
  • it->second is 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:

TextOutput
pen: 40 left
book: out of stock
bag: not sold here
perks: 30

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 default in every switch.
  • Keep variables in the narrowest scope (if-initialisers help).

Common mistakes

Missing break

Avoid

case 1: save();
case 2: quit(); break;

Prefer

case 1: save(); break;
case 2: quit(); break;

Without break, choosing 1 also quits.

Switching on a string

Avoid

switch (cmd) { case "exit": ... }

Prefer

if (cmd == "exit") { ... }

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

  1. 1
    Write a program that reads a year and prints whether it is a leap year.
  2. 2
    Write 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?
Practise this topic