cpp / beginner
Snippet
Switch Statements for Multiple Choices
A switch statement provides a clean way to handle multiple conditional branches based on a single variable value. Instead of chaining many if-else statements, switch allows you to compare one variable against multiple constant values. Each case is checked sequentially until a match is found or the default case is reached. The break statement prevents fall-through to subsequent 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 << "Invalid day" << std::endl;}return 0;}
Breakdown
1
switch(day) {
Begins switch block, evaluates the day variable
2
case 1:
Checks if day equals 1, executes next line if true
3
break;
Exits the switch block, preventing fall-through to case 2
4
default:
Executes if no case matches the variable value