cpp / beginner
Snippet
Switch Statements for Menu Choices
Switch statements provide an efficient way to handle multiple discrete values. Instead of chaining many if-else conditions, you compare one variable against multiple possible values (cases). Each case ends with a break statement to prevent falling through to the next case. The default case handles any value not explicitly matched, serving as a catch-all for invalid inputs.
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
29
30
31
#include <iostream>using namespace std;int main() {int choice;cout << "Select an option:" << endl;cout << "1. New Game" << endl;cout << "2. Load Game" << endl;cout << "3. Settings" << endl;cout << "4. Exit" << endl;cin >> choice;switch (choice) {case 1:cout << "Starting new game..." << endl;break;case 2:cout << "Loading saved game..." << endl;break;case 3:cout << "Opening settings menu..." << endl;break;case 4:cout << "Goodbye!" << endl;break;default:cout << "Invalid choice!" << endl;}return 0;}
Breakdown
1
switch (choice) {
Switch keyword begins evaluation of the choice variable against cases
2
case 1:
Label matching when choice equals 1 - code after colon executes
3
break;
Exit switch immediately after completing case 1 - without it, execution continues to next case
4
default:
Special case executed when no other case matches the input value