C++ switch Statement
switch chooses one path from many, by the value of an integer, a char or an enum (not a string or a double).
#include <iostream>
int main() {
int day = 3;
switch (day) {
case 1:
std::cout << "Monday\n";
break;
case 2:
std::cout << "Tuesday\n";
break;
case 3:
std::cout << "Wednesday\n";
break;
default:
std::cout << "Another day\n";
}
}
Wednesday
Fall through
Without break the code goes on to the next case. It is useful to group cases, but it is also a common bug. Use [[fallthrough]]; when you really want it.
#include <iostream>
int main() {
char grade = 'B';
switch (grade) {
case 'A':
case 'B':
std::cout << "Good ";
[[fallthrough]];
case 'C':
std::cout << "Pass\n";
break;
default:
std::cout << "Fail\n";
}
}
Good Pass
Switch with an enum class
#include <iostream>
enum class Level { Low, Medium, High };
int main() {
Level level = Level::High;
switch (level) {
case Level::Low: std::cout << "All fine\n"; break;
case Level::Medium: std::cout << "Be careful\n"; break;
case Level::High: std::cout << "Danger\n"; break;
}
}
Danger
If you forget one value of the enum (and no default), the compiler warns you with -Wall.
Variables inside a case
#include <iostream>
int main() {
int n = 1;
switch (n) {
case 1:
int x = 10; // jumping over this initialization from another case is an error
std::cout << x << '\n';
break;
case 2:
std::cout << "two\n";
break;
}
}
Scope.cpp: In function 'int main()':
Scope.cpp:10:14: error: jump to case label
10 | case 2:
| ^
Scope.cpp:7:17: note: crosses initialization of 'int x'
7 | int x = 10; // jumping over this initialization from another case is an error
| ^
Put the case code in braces { } when you declare variables in it.
Switch with an initializer (C++17)
#include <iostream>
int main() {
switch (int code = 404; code) {
case 200: std::cout << "OK\n"; break;
case 404: std::cout << "Not found\n"; break;
default: std::cout << "Other\n";
}
}
Not found
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |