01 / 21

Switch Statements
in C++

Master the switch statement for clean multi-way branching, understand fall-through behavior, and learn when to choose switch over if-else chains.

C++

What Is a Switch Statement?

A switch statement evaluates a single expression once and compares its value against a list of constant labels. When a match is found, the program executes the code associated with that label.

Multi-way branching
Test one value against many cases in a single block
Integral types only
Works with int, char, and enum values, not strings or floats

Why Use Switch Over If-Else?

When you have multiple discrete values to test for the same variable, a switch statement is often cleaner and can be more efficient. Compilers can optimize switch into a jump table, making lookups constant-time.

Readability
Each case is clearly labeled, making the code self-documenting
Performance
Compilers can use jump tables for \( O(1) \) dispatch
Maintainability
Adding a new case is a single block, no re-nesting needed

Anatomy of a Switch Statement

switch(expression) no match case 1: code block A break; case 2: code block B break; case 3: code block C break; default: code block D continue after switch

The Syntax in Detail

switch (expression) { case constant1: // code if expression == constant1 break; case constant2: // code if expression == constant2 break; default: // code if no case matched break; }
1
Expression is evaluated exactly once and must produce an integral type
2
Case labels are compile-time constants: literals, const variables, or enum values
3
break prevents fall-through to the next case
4
default is optional but highly recommended for robustness

Understanding Fall-Through

Fall-through is the default behavior in C++: if you omit the break after a case, execution continues into the next case's code, regardless of whether that case's label matches.

case 1: print("A") no break! case 2: print("B") no break! case 3: print("C") break; If input = 1, output: A B C FALL THROUGH

Intentional Fall-Through

Sometimes fall-through is deliberately useful: when multiple cases should execute the same code, you can stack case labels together.

switch (day) { case 1: // Monday case 2: // Tuesday case 3: // Wednesday case 4: // Thursday case 5: // Friday cout << "Weekday"; break; case 6: case 7: cout << "Weekend"; break; }

Switch vs If-Else

switch if-else
Expression type Integral only (int, char, enum) Any boolean expression
Comparison Equality check only Any operator (<, >, !=, ranges)
Multiple values Stack case labels Use || operators
Readability (many cases) Excellent Degrades quickly
Performance hint Jump table possible Sequential checks
Range checks Not supported Natural fit

How to Write a Switch Statement

1
Identify the variable: it must be an integral type (int, char, enum)
2
List all expected values: each becomes a case label with a compile-time constant
3
Write case blocks: add the logic for each case, keeping it focused and short
4
Add break; at the end of every case unless you intentionally want fall-through
5
Include default: always handle unexpected values for robustness

Example 1: Simple Grade Checker

char grade = 'B'; switch (grade) { case 'A': cout << "Excellent!"; break; case 'B': cout << "Good job!"; // ✓ This runs break; case 'C': cout << "Keep trying"; break; default: cout << "Invalid grade"; break; }

Example 2: Fall-Through in Action

int month = 3; switch (month) { case 12: case 1: case 2: cout << "Winter"; break; case 3: case 4: case 5: cout << "Spring"; // ✓ This runs break; case 6: case 7: case 8: cout << "Summer"; break; default: cout << "Autumn"; break; }

Example 3: Enums with Switch

enum class Color { Red, Green, Blue }; Color c = Color::Green; switch (c) { case Color::Red: cout << "Stop"; break; case Color::Green: cout << "Go"; // ✓ This runs break; case Color::Blue: cout << "Slow down"; break; }

Variables Inside Cases

Declaring variables inside a case without braces can cause cross-initialization errors. Each case shares the same scope unless you add explicit braces.

✕ Wrong
case 1: int x = 5; break; case 2: ...
Jump to case 2 skips initialization of x
✓ Correct
case 1: { int x = 5; break; }
Braces create a local scope for x

C++17: [[fallthrough]] Attribute

Modern compilers often warn when a case lacks a break, as this can be an unintentional bug. The [[fallthrough]] attribute explicitly marks intentional fall-through, silencing these warnings and improving code clarity.

switch (level) { case 3: applyBonus(); [[fallthrough]]; // intentional case 2: applyDiscount(); [[fallthrough]]; case 1: applyBase(); break; }

Common Mistakes

✕ Forgetting break
Causes unintended fall-through. Every case should end with break unless you intentionally want fall-through.
✕ Non-constant case
Case labels must be compile-time constants. Variables or function calls as labels cause a compilation error.
✕ Using strings or floats
Switch only works with integral types. Using a string or double as the switch expression won't compile.
✕ Missing default
Omitting default means unmatched values silently do nothing. Always include default for defensive coding.

Summary Cheat Sheet

Concept Key Point
Expression type int, char, enum (integral only)
Case labels Must be compile-time constants
break Exits the switch; prevents fall-through
Fall-through Without break, execution continues to next case
default Catches all unmatched values; recommended
[[fallthrough]] C++17 attribute for intentional fall-through
Variable scope Use { braces } in cases with declarations

Question 1 of 5

What happens if you omit the break statement at the end of a case in a switch block?

Question 2 of 5

What is the output of this program?

Question 3 of 5

Which of the following cannot be used as a switch expression in C++?

Question 4 of 5

What is the purpose of the [[fallthrough]] attribute introduced in C++17?

Question 5 of 5

What is the problem with this switch statement?