smirking teapot

“I’m not an expert, I’m just a dude.” -Scott Schurr, CppCon 2015.

std::unreachable in C++23

Posted at — Apr 23, 2026 ยท 1 min read

C++23 introduced std::unreachable() (defined in <utility>) to explicitly mark code paths that should never execute. Before this, we relied on compiler-specific builtins like __builtin_unreachable() (GCC/Clang) or __assume(false) (MSVC).

int fast_mod4(int x) {
    switch (x % 4) {
        case 0: return 0;
        case 1: return 1;
        case 2: return 2;
        case 3: return 3;
    }
    std::unreachable();  // compiler can optimize away the fallthrough
}

Invoking std::unreachable() at runtime is undefined behavior -> the compiler is free to assume it never happens and optimize accordingly. This is strictly a hint for the optimizer, not a safety mechanism.