Loading lessons...
Switch Statements
Switch Statements
When you test one value against many possible values, a switch keeps the code tidy. It replaces a long chain of else ifs.
The shape
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// run when nothing matches
}
- Evaluate
expressiononce. - Compare it against each
casevalue. - When a value matches, run its statements.
- The
breakjumps out of the switch. - If nothing matched,
defaultruns.
An example
#include <iostream>
using namespace std;
int main() {
int day = 4;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
default:
cout << "Not a day I recognize" << endl;
}
return 0;
}
With day = 4, the case 4 matches and prints "Thursday".
When to use a switch
LearnCpp 8.5 says a switch is the natural fit when you test a single variable against several fixed constant values. It reads its labels at a glance. Compare one value to constants with a switch; here the if/else chain.
TL;DR
switch (expr)runs the matchingcase, thenbreakends the switch.defaultruns when no case matched.- It is the cleanest way to compare one value against many constants.
- Forgetting
breakmakes the execution fall through to the next case.