capypad
0 day streak
cpp / beginner
Snippet

Menu Selection with Switch

The switch statement checks a variable against multiple possible values. Each case runs code if it matches. The break prevents falling through to the next case. Default handles any unmatched value.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
int main() {
int choice = 2;
switch (choice) {
case 1:
std::cout << "You chose Option 1" << std::endl;
break;
case 2:
std::cout << "You chose Option 2" << std::endl;
break;
case 3:
std::cout << "You chose Option 3" << std::endl;
break;
default:
std::cout << "Invalid choice" << std::endl;
}
return 0;
}
Breakdown
1
switch (choice) { ... }
Evaluates the variable and jumps to matching case
2
case 2:
Label that matches when choice equals 2
3
break;
Exits the switch block, no fall-through