The switch Statement in C++
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.
Dispatch on one value
switch (day) jumps straight to case 3: for Wednesday — one expression tested against many constant labels.
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.
default handles the rest
default: runs when nothing matched — the else of the switch world, ideal for invalid-input handling.
Constants only
Case labels must be compile-time constants (literals, enums, constexpr) — ranges and variables are not allowed.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.