cpp / beginner
Snippet
The Switch Statement
A switch statement provides an efficient way to handle multiple conditional branches based on a single variable's value. It compares the variable against different cases and executes the matching one. The break statement prevents fall-through to subsequent cases. The default case handles any value that doesn't match listed cases.
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)
Expression evaluated once against cases
2
case 3:
Matches value 3, executes code here
3
break;
Exits switch block, no fall-through