C++ Switch Statement: Jump Tables, Rules & Modern [[fallthrough]]

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.

Switch Syntax with C++17 [[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;
}
Expected Console Output:
[CRITICAL]: Send emergency notification!
[HIGH]: Alert duty engineer immediately.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Can you use std::string or floating-point numbers in a C++ switch statement?

No. In standard C++, switch expressions MUST evaluate to an integral or enumeration type (int, char, enum, short, bool). For strings or floats, use if-else ladders or hash-based dispatch.

Q2. What is the C++17 [[fallthrough]] attribute used for?

By default, if you omit 'break' in a switch case, execution falls through into the next case, which often triggers compiler warnings. Adding the '[[fallthrough]];' attribute explicitly signals to the compiler and human reviewers that the fall-through was completely intentional.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

C++ If-Else

Compare when to choose switch vs if-else ladders.

C++ While Loop

Using switch inside menu-driven loop systems.

Break & Continue

Controlling switch block termination.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!