capypad
0 day streak
cpp / beginner
Snippet

Switch Statements for Multiple Choices

A switch statement provides an efficient way to execute different code based on a variable's value. It compares a variable against multiple constant values (cases). The break keyword prevents fall-through to subsequent cases. The default case handles any value not matching the listed cases. Switch is often clearer than multiple if-else chains for comparing one value against many options.

snippet.cpp
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
#include <iostream>
 
int main() {
int grade = 3;
switch (grade) {
case 1:
std::cout << "Excellent!" << std::endl;
break;
case 2:
std::cout << "Good job!" << std::endl;
break;
case 3:
std::cout << "Satisfactory." << std::endl;
break;
case 4:
std::cout << "Needs improvement." << std::endl;
break;
case 5:
std::cout << "Not passed." << std::endl;
break;
default:
std::cout << "Invalid grade." << std::endl;
break;
}
return 0;
}
Breakdown
1
int grade = 3;
Declares integer variable storing a grade value
2
switch (grade) {
Begins switch statement evaluating the grade variable
3
case 1:
Label matching grade value 1
4
std::cout << "Excellent!" << std::endl;
Output for excellent grade
5
break;
Exits switch statement, prevents fall-through
6
case 2:
Label matching grade value 2
7
std::cout << "Good job!" << std::endl;
Output for good grade
8
break;
Exits switch statement
9
case 3:
Label matching grade value 3
10
std::cout << "Satisfactory." << std::endl;
Output for satisfactory grade
11
break;
Exits switch statement
12
default:
Catches any grade value not explicitly listed
13
std::cout << "Invalid grade." << std::endl;
Output for invalid grade values