switch Statement
else if statements when you are testing the same variable against many possible values.Basic Syntax
#include <iostream>
using namespace std;
int main() {
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
default:
cout << "Unknown day" << endl;
break;
}
return 0;
}
// Output: WednesdayFallthrough and break
break is one of the most common C++ bugs. Without it, execution silently continues into the next case, printing or running code you never intended.int x = 1;
switch (x) {
case 1:
cout << "One" << endl;
// missing break! falls through into case 2
case 2:
cout << "Two" << endl;
break;
case 3:
cout << "Three" << endl;
break;
}
// Output:
// One
// Two <- ran even though x was 1, because of the missing breakIntentional Fallthrough: [[fallthrough]] (C++17)
[[fallthrough]] attribute so you can mark that omission as deliberate. It documents your intent to readers and to static analyzers/compilers, which otherwise often warn about a missing break.char grade = 'B';
switch (grade) {
case 'A':
case 'B':
cout << "Well done!" << endl;
break;
case 'C':
cout << "Passed." << endl;
[[fallthrough]]; // intentional: also print the note below
case 'D':
cout << "Consider retaking the course." << endl;
break;
default:
cout << "Invalid grade." << endl;
}case 'A': directly above case 'B':) does not need [[fallthrough]] — the attribute is only useful when a case has its own statements and then intentionally falls into the next one.Switching on Enums
switch pairs especially well with enumerations, since each enumerator is a distinct integral constant. Many compilers will even warn you if an enum-based switch does not handle every enumerator, which helps catch bugs when new enum values are added later. See the Enumerations page for more on defining enums.
enum class Direction { North, South, East, West };
Direction d = Direction::East;
switch (d) {
case Direction::North:
cout << "Heading North" << endl;
break;
case Direction::South:
cout << "Heading South" << endl;
break;
case Direction::East:
cout << "Heading East" << endl;
break;
case Direction::West:
cout << "Heading West" << endl;
break;
}
// Output: Heading Eastswitch vs if/else Chains
Situation | Prefer |
|---|---|
Testing one variable against many constant values | switch |
Testing complex or range-based conditions (a < x < b) | if / else if |
Switching on strings or floating-point values | if / else if |
Enum-driven logic where the compiler can check coverage | switch |
Key Points
switch compares one value against several constant case labels.
Without break, execution falls through into the next case - always add break unless fallthrough is intentional.
[[fallthrough]] (C++17) documents intentional fallthrough and silences warnings.
switch works only with integral/enum types, not strings or floats.
default handles any value that does not match a case, and is optional.