capypad
0 day streak
cpp / beginner
Snippet

Switch Statements: Multi-Way Branching

A switch statement provides an elegant way to handle multiple conditions based on a single variable's value. It evaluates the expression once and jumps to the matching case label. The break keyword prevents fall-through to subsequent cases.

snippet.cpp
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 grade = 2;
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;
default:
std::cout << "Needs improvement" << std::endl;
}
return 0;
}
Breakdown
1
switch (grade) {
Begins switch statement, evaluates the grade variable
2
case 1:
Label for when grade equals 1
3
std::cout << "Excellent!" << std::endl;
Output executed when case 1 matches
4
break;
Exits the switch block, preventing fall-through
5
default:
Executed when no case matches the value