C++•Switch Statement
C++ Switch Statements: Cases, Fallthrough, and [[fallthrough]]
The C++ switch statement jumps directly to matching case labels, using jump tables for O(1) performance.
Syntax
switch (integral_expr) {
case CONST_VAL:
// code
break;
default:
// code
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| break | Keyword | Exits switch block to prevent fallthrough. |
| default | Label | Executes when no case matches. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C++ locally:
#include <iostream>
enum class LogLevel { INFO, WARNING, ERROR, CRITICAL };
int main() {
LogLevel currentLevel = LogLevel::ERROR;
switch (currentLevel) {
case LogLevel::INFO:
std::cout << "[INFO] System operating normally.\n";
break;
case LogLevel::WARNING:
std::cout << "[WARN] Non-critical latency observed.\n";
break;
case LogLevel::ERROR:
case LogLevel::CRITICAL:
std::cout << "[CRITICAL] Immediate developer intervention required!\n";
break;
default:
std::cout << "Unknown log status.\n";
break;
}
return 0;
}Expected Output:
[CRITICAL] Immediate developer intervention required!
How It Works: Step-by-Step
- Line 3: Defines a scoped enum class for type-safe state values.
- Lines 15-17: Combines ERROR and CRITICAL cases into a single handler.
Key Concepts
- switch in C++ only operates on integral types (int, char, enum).
- Compiler jump tables make switch significantly faster than multiple if/else chains.
- Prefer enum class over raw enums to prevent namespace pollution.
Common Mistake: Attempting to use std::string in a C++ switch statement
C++ switch statements only accept integral types. For strings, use if/else or hash mapping.
❌ Incorrect
std::string s = "test";
switch(s) { /* Compile Error: switch quantity not an integer */ }✅ Correct
if (s == "test") { /* Use standard string equality */ }Related C++ Tutorials & Compiler
C++ If...Else Statements and Boolean Logic with Examples
Learn decision-making structures in C++ with if, else if, else, and C++17 init-statements.
C++ For Loops and Range-Based For Loops (C++11)
Master traditional counter loops and modern C++11 range-based for loops over collections.
C++ Functions: Pass-by-Value, Pass-by-Reference, and Const
Understand function parameters, pass-by-value vs pass-by-reference (&), and const correctness.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.