C++:C++ Switch Statements: Cases, Fallthrough, and [[fallthrough]]
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:

ParameterTypeDescription
breakKeywordExits switch block to prevent fallthrough.
defaultLabelExecutes when no case matches.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler