Learn C++
#include "controlflow/switch.hpp"

The switch Statement in C++

//concept

switch dispatches on an integer-like value (int, char, enum) to labeled case branches — cleaner than long == chains when one variable decides everything. Execution falls through from the matching case into every case below it unless break stops it, a behavior that is occasionally useful (shared handling) but usually a bug when forgotten.

Cases must be compile-time constants, and default catches unmatched values. Modern compilers warn on missing breaks and unhandled enum values, turning the two classic switch mistakes into build-time messages.

//how it works
1

Dispatch on one value

switch (day) jumps straight to case 3: for Wednesday — one expression tested against many constant labels.

2

break stops fallthrough

Without break, execution slides into the next case's statements too. End every case with break (or return) unless sharing is deliberate.

3

default handles the rest

default: runs when nothing matched — the else of the switch world, ideal for invalid-input handling.

4

Constants only

Case labels must be compile-time constants (literals, enums, constexpr) — ranges and variables are not allowed.

//example
#include <iostream>
 
int main() {
int day = 3;
switch (day) {
case 1: std::cout << "Mon" << std::endl; break;
case 3: std::cout << "Wed" << std::endl; break;
default: std::cout << "other" << std::endl; break;
}
return 0;
}
Output
Wed
1day is 3, so control jumps directly to case 3:, skipping case 1: entirely.
2Wed prints, then break exits the switch — without it, default's other would print too.
3Exactly one line appears, proving dispatch hit precisely one case.
//use cases
Menu and command dispatch where one integer or char selects behavior
State machines with enum states and one case per state
Grouping several cases above shared code (case 6: case 7: weekend handling)
Letting -Wswitch warn when a new enum value lacks its case

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.