2.3 The switch Statement
When you are testing an integer, character, or enum value and need to branch many ways on its value, a long chain of else if becomes verbose. A switch can make the structure clearer.
switch (op) {
case '+':
std::cout << a + b << std::endl;
break;
case '-':
std::cout << a - b << std::endl;
break;
default:
std::cout << "Unsupported" << std::endl;
break;
}A switch matches the value in the parentheses against each case. Once a case matches, execution starts from there.
switch works with integral and enumeration types such as int, char, and enum; it cannot be used directly with double or std::string.break and fall-through
break exits the switch. If you forget it, execution continues into the following case, a behavior called fall-through.
Sometimes you can use fall-through deliberately so several cases share the same code:
switch (grade) {
case 'A':
case 'B':
std::cout << "Pass" << std::endl;
break;
case 'C':
std::cout << "Just pass" << std::endl;
break;
default:
std::cout << "Fail" << std::endl;
break;
}Here 'A' and 'B' share one output, because 'A' has no break and falls through to 'B'. Most of the time, however, a missing break is a bug, so be careful.
default
default handles every case that did not match, similar to the else in an if-else if-else. It is good practice to always include default, even if it only prints a message, so the program behaves predictably on unexpected input.