cpp / beginner
Snippet
Switch Statement: Multi-Way Branching
A switch statement compares a variable against multiple possible values (cases). When a match is found, the corresponding code block runs. The break statement prevents the program from checking remaining cases. The default case runs when no case matches.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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;default:std::cout << "Unknown day" << std::endl;}return 0;}
Breakdown
1
switch (day) {
Begins switch statement, evaluating the variable 'day'
2
case 3:
Label that matches when day equals 3
3
std::cout << "Wednesday" << std::endl;
Code executed when case 3 matches
4
break;
Exits the switch block, preventing fall-through to next cases
5
default:
Catches all cases that don't match any specific case