The switch statement is a multi-way branch selection control structure. It tests an expression against a list of constant integral values (case labels). Compilers often optimize switch into an $O(1)$ Jump Table, executing substantially faster than long if-else ladders.
[[fallthrough]]#include <iostream>
enum class Severity { Low, Medium, High, Critical };
void processAlert(Severity level) {
switch (level) {
case Severity::Low:
std::cout << "[INFO]: Minor event logged.\n";
break;
case Severity::Medium:
std::cout << "[WARN]: Check system diagnostics.\n";
break;
case Severity::Critical:
std::cout << "[CRITICAL]: Send emergency notification!\n";
[[fallthrough]]; // C++17 attribute: Intentionally cascades to High
case Severity::High:
std::cout << "[HIGH]: Alert duty engineer immediately.\n";
break;
default:
std::cout << "[UNKNOWN]: Invalid severity code.\n";
break;
}
}
int main() {
processAlert(Severity::Critical);
return 0;
}
[CRITICAL]: Send emergency notification![HIGH]: Alert duty engineer immediately.
Boost your C++ proficiency by studying these closely connected core modules:
Compare when to choose switch vs if-else ladders.
Using switch inside menu-driven loop systems.
Controlling switch block termination.