C++ Switch
When you need to compare one variable against many possible values, a long chain of else if statements can get messy. The switch statement offers a cleaner way to pick one block of code out of many based on a single value.
A switch statement checks a variable against a list of case values. When it finds a match, it runs the code for that case. It is perfect for menus, day names, grades, and any situation with a fixed set of choices.
How switch works
You write switch followed by the variable in parentheses. Inside the braces, each case lists a possible value. The break keyword ends a case so the program jumps out of the switch. The optional default runs when no case matches.
A switch on the day of the week
#include <iostream>
using namespace std;
int main() {
int day = 3;
switch (day) {
case 1:
cout << "Monday\n";
break;
case 2:
cout << "Tuesday\n";
break;
case 3:
cout << "Wednesday\n";
break;
default:
cout << "Another day\n";
}
return 0;
}The default case
The default case is like the else in an if chain. It catches any value that none of the cases matched. It is optional, but including it is good practice so your program always has a sensible response.
A simple menu with default
#include <iostream>
using namespace std;
int main() {
char choice = 'B';
switch (choice) {
case 'A':
cout << "You chose Start.\n";
break;
case 'B':
cout << "You chose Settings.\n";
break;
case 'C':
cout << "You chose Quit.\n";
break;
default:
cout << "Unknown option.\n";
}
return 0;
}switch vs if...else
When to reach for a switch
Exercise: C++ Switch
Can a C++ switch statement use std::string values directly as case labels?