4.3 — switch: many choices
Read one box at a time. No rush.
Picking from a list#
When you check one variable against many exact values, switch is neat and tidy.
C++
int day { 3 }; switch (day){case 1: std::cout << "Monday\n"; break;case 2: std::cout << "Tuesday\n"; break;case 3: std::cout << "Wednesday\n"; break;default: std::cout << "Some other day\n"; break;}Output
WednesdayThe parts#
switch (day)= the value to check.case 3:= "if the value is 3, start here".break;= "stop, leave the switch".default:= "if no case matched".
Do not forget break#
Without break, C++ keeps going into the next case! This is called fall-through.
C++ — wrong ✗
switch (2){case 1: std::cout << "one ";case 2: std::cout << "two ";case 3: std::cout << "three ";}Output
two threeWatch out
End every case with break; unless you really want fall-through.
Sharing code between cases#
Stacking cases on purpose is fine:
C++
char c { 'e' }; switch (c){case 'a':case 'e':case 'i':case 'o':case 'u': std::cout << "vowel\n"; break;default: std::cout << "consonant\n"; break;}When to use switch
switch only works with whole numbers, chars and enums (see 10.1 — enum class: a set of named options). It cannot check ranges like > 10, and it cannot check strings. Use if for those.
Tip: press ← / → to move between lessons, / to search.