switch Statements
Syntax
switch (expression) {
case value1:
...
break;
case value2:
case value3: // several values, same code
...
break;
default: // no case matched
...
}
Rules
- The expression must be an integer, char or enum (not
double, notstd::string) - Case labels must be compile-time constants and unique
breakexits the switch; without it execution falls through into the next casedefaultis optional but recommended
Fall-through
Sometimes intentional (grouping cases). Mark intentional fall-through with [[fallthrough]]; (C++17) to silence warnings and tell readers it's on purpose.
Variables inside cases
Declaring a variable in a case needs its own block:
case 1: {
int x = 5;
...
break;
}
switch with enums ✅
enum class Category { Food, Rent, Travel };
switch (cat) {
case Category::Food: ...
}
With -Wall, the compiler warns if you forget an enum value — a great safety net (so consider leaving out default for enums).
switch with initializer (C++17)
switch (auto c = get_choice(); c) { ... }
switch vs if-else
| switch | if-else |
|---|---|
| One value vs constants | Any conditions, ranges |
| Clean menus | Strings, doubles, complex logic |
| Can be faster (jump table) | Checks in order |
Example
#include <iostream>
enum class Category { Food, Rent, Travel, Fun };
const char* icon(Category c) {
switch (c) { // no default: the compiler warns if a value is missing
case Category::Food: return "🍜";
case Category::Rent: return "🏠";
case Category::Travel: return "🚌";
case Category::Fun: return "🎉";
}
return "?";
}
int days_in_month(int month) {
switch (month) {
case 2:
return 28;
case 4: case 6: case 9: case 11: // grouped cases
return 30;
default:
return 31;
}
}
int main() {
for (int choice = 1; choice <= 4; ++choice) {
std::cout << "Menu choice " << choice << ": ";
switch (choice) {
case 1:
std::cout << "Add expense\n";
break;
case 2:
std::cout << "View report\n";
break;
case 3:
std::cout << "Export... ";
[[fallthrough]]; // intentional fall-through
case 4:
std::cout << "Exit\n";
break;
default:
std::cout << "Unknown\n";
}
}
std::cout << "Feb: " << days_in_month(2) << ", Jun: " << days_in_month(6) << ", Dec: " << days_in_month(12) << '\n';
std::cout << "Rent icon: " << icon(Category::Rent) << ", Travel icon: " << icon(Category::Travel) << '\n';
char op = '*';
int a = 6, b = 7;
switch (op) {
case '+': std::cout << a + b << '\n'; break;
case '*': std::cout << a << " * " << b << " = " << a * b << '\n'; break;
default: std::cout << "unsupported\n";
}
return 0;
}
/* Output:
Menu choice 1: Add expense
Menu choice 2: View report
Menu choice 3: Export... Exit
Menu choice 4: Exit
Feb: 28, Jun: 30, Dec: 31
Rent icon: 🏠, Travel icon: 🚌
6 * 7 = 42
*/