C++ Switch
A switch statement matches one value against a list of cases. The case that matches the value runs its code.
Matching one case
The value 3 matches case 3. That case prints its day name, and its break ends the switch.
#include <iostream>
int main() {
int day = 3;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
case 4:
std::cout << "Thursday" << std::endl;
break;
}
return 0;
}Missing break runs the next case
Case 2 has no break in this program. The run continues into case 3, so its line prints too.
#include <iostream>
int main() {
int day = 2;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
case 3:
std::cout << "Wednesday" << std::endl;
break;
}
return 0;
}Default catches the rest
The value 9 matches no case here. The default case runs and prints its line.
#include <iostream>
int main() {
int day = 9;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
default:
std::cout << "Unknown day" << std::endl;
break;
}
return 0;
}Example
#include <iostream>
int main() {
int day = 6;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
case 4:
std::cout << "Thursday" << std::endl;
break;
case 5:
std::cout << "Friday" << std::endl;
break;
case 6:
std::cout << "Saturday" << std::endl;
break;
case 7:
std::cout << "Sunday" << std::endl;
break;
default:
std::cout << "Unknown day" << std::endl;
break;
}
return 0;
}Key points
- Each case names a value to match against the switch value.
- break ends a case so the next case does not run.
- A case runs the lines between its label and its break.
- The default case runs when no case matches.
- A switch fits a value with a small set of named cases.
In this example, day holds 6. The switch tests the value against each case in order. Case 6 is the match, so its line prints the day name Saturday. Its break then ends the switch.
Note
Without break, a matched case runs the next case as well.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does break do at the end of a case?