cpp / beginner
Snippet
Switch Statement: Handling Multiple Cases
Switch statements test a variable against multiple possible values. It is often cleaner than multiple if-else chains when comparing one value against many constants. The break prevents fall-through to next case.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>using namespace std;int main() {int day = 3;switch (day) {case 1:cout << "Monday" << endl;break;case 2:cout << "Tuesday" << endl;break;case 3:cout << "Wednesday" << endl;break;default:cout << "Unknown day" << endl;}return 0;}
Breakdown
1
switch (day) {
Begin switch with variable to test
2
case 3:
Match specific value - Wednesday
3
break;
Exit switch, prevents falling through to next case
4
default:
Executes when no case matches