Learn C++ · lesson 16 of 61 · about 8 minutes
switch
Three doors: choose between exact values with switch, case, break and default, and let cases share code.
What you'll learn
- Write a switch
- Use break to stop fall-through
- Handle everything else with default
Many exact matches
The cave ends at three doors marked a, b and c. switch (door) compares the value with each case. A matching case runs until break, and default catches everything else.
switch works with whole numbers and chars, such as an int or a char, but not with std::string.
The three doors
#include <iostream>
int main() {
char door = 'b';
switch (door) {
case 'a':
std::cout << "Just old bones.\n";
break;
case 'b':
std::cout << "A sleeping dragon!\n";
break;
case 'c':
std::cout << "Treasure!\n";
break;
default:
std::cout << "That door doesn't exist.\n";
}
}Output
A sleeping dragon!break and falling through
Without break, the program carries on into the next case's code. That's called falling through, it's usually a bug, and g++ warns about it. Cases with nothing between them are different: stacking them on purpose lets them share code, so case 'b': and case 'B': can run the same lines.
Menu choices
#include <iostream>
int main() {
char choice = 'b';
switch (choice) {
case 'a':
std::cout << "Start lesson\n";
break;
case 'b':
case 'B':
std::cout << "Open shop\n";
break;
default:
std::cout << "Unknown option\n";
}
}Output
Open shopA variable inside a case
A variable created in one case is still visible in the cases below it, so C++ won't let the switch jump past where it's created: you get jump to case label. If a case needs its own variable, put that case's code in braces: case 'c': { ... break; }.
Tip
switch doesn't work with std::string. For text, use if / else if with ==.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.