cpp / beginner
Snippet
Switch Statements: Handling Multiple Cases Efficiently
A switch statement provides an efficient way to handle multiple conditions when a variable can have several possible values. Instead of writing many if-else chains, you compare a single expression against multiple case values. When a match is found, that case's code executes. The break keyword prevents the program from falling through to the next case. If no case matches, the default block runs. Switch works with integers, characters, and enum types but cannot compare ranges or strings.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>int main() {int day = 3;switch (day) {case 1:std::cout << "Monday" << std::endl;break;case 2:std::cout << "Tuesday" << std::endl;break;case 3:std::cout << "Wednesday" << std::endl;break;case 4:std::cout << "Thursday" << std::endl;break;case 5:std::cout << "Friday" << std::endl;break;default:std::cout << "Weekend" << std::endl;break;}return 0;}
Breakdown
1
switch (day)
Expression in parentheses is evaluated once and compared against cases
2
case 3:
Label matching the value of day (3 = Wednesday)
3
break;
Exits the switch block, preventing fall-through to remaining cases
4
default:
Optional case that executes when no other case matches