skip to content

In C++23, what do [[assume(expr)]] and std::unreachable() tell the optimizer, and what happens if the assumption is false?

level: middleimportance: should knowfreq 35%

answer

  1. promises, not checks
  2. the expression is never evaluated
  3. false assumption: undefined behaviour
  4. assert checks; assume trusts

basics

~10 s

Both are promises the compiler may optimize on: [[assume(expr)]] says expr is true at that point, std::unreachable() says control never gets there. Neither checks anything; if the promise is false the behaviour is undefined.

solid answer

~50 s

C++23 added two ways to hand the optimizer a fact it cannot prove. `[[assume(expr)]];` is an attribute on a null statement: the expression is **not evaluated**, and if it would not be `true` at that point, evaluation of the assumption has **undefined behaviour**; Apple clang 21 uses `[[assume(len >= 0)]]` to compile `len / 4` as a single logical shift. `std::unreachable()`, declared `[[noreturn]]` in `<utility>`, has the precondition `false`, so calling it is always undefined; placed after an exhaustive `switch` it lets the compiler drop the fall-through path. Neither is a check: unlike `assert`, they do nothing in debug builds and turn a wrong belief into undefined behaviour the optimizer exploits. Side effects in an assumption, such as `++y`, never happen. Common practice wraps them in a macro that asserts in debug builds and assumes in release.

code

cpp · 22 lines
cpp
#include <cstdio>
#include <utility>

enum class Kind { Data, Ack, Ping };

int header_size(Kind k) {
    switch (k) {
    case Kind::Data: return 12;
    case Kind::Ack:  return 4;
    case Kind::Ping: return 2;
    }
    std::unreachable();      // C++23: reaching here is undefined behaviour
}

int scale(int len) {
    [[assume(len >= 0)]];    // C++23: not evaluated; false here is UB
    return len / 4;          // no negative-rounding fix-up needed
}

int main() {
    std::printf("%d %d\n", header_size(Kind::Ack), scale(10));
}

go deeper

for a junior

Recall that both features are hints to the optimizer, not checks, and that a wrong hint makes the program's behaviour undefined.

for a middle

Explain that the assumption's expression is never evaluated, what std::unreachable's impossible precondition means, and how both differ from assert.

for a senior

Show where assumptions pay off, such as division and exhaustive switches, and how a false one reproduces the deleted-check bugs; pair each with a debug assertion.

for a principal

Set a team rule for assumptions: hot paths only, internal invariants only, always backed by a debug check through one project macro.

## Two ways to give the optimizer a fact Optimizers already exploit the facts that undefined behaviour gives them. C++23 lets the programmer add facts explicitly: - **`[[assume(expr)]];`** is the **assumption attribute**, applied to a null statement. The expression is contextually converted to `bool` but **not evaluated**. If it would evaluate to `true` at that point, the assumption has no effect; otherwise, evaluation of the assumption has undefined behaviour. C++26 calls this **runtime-undefined behaviour**, which is undefined except during constant evaluation. - **`std::unreachable()`**, declared `[[noreturn]] void unreachable();` in `<utility>`, has the precondition "`false` is `true`". That precondition can never hold, so calling the function is always undefined behaviour. Its purpose is to mark a point that control never reaches. Both predate C++23 as vendor extensions, such as GCC's and Clang's `__builtin_unreachable` and Clang's `__builtin_assume`; the standard forms are portable, and Apple clang 21 reports `__has_cpp_attribute(assume)` as `202207`. ## What the optimizer does with them The draft's own example shows the intent: ```cpp int divide_by_32(int x) { [[assume(x >= 0)]]; return x/32; // the instructions produced may omit handling of negative values } ``` Signed division rounds towards zero, so dividing a possibly negative `int` by a power of two needs a correction step. With the assumption, Apple clang 21 at `-O2` compiles `len / 4` to a single logical shift right; without it, to an add, a compare, a conditional select and an arithmetic shift. The standard does not require any particular use: implementations are free to ignore assumptions. `std::unreachable()` serves exhaustive `switch` statements and similar control flow: ```cpp switch (k) { case Kind::Data: return 12; case Kind::Ack: return 4; case Kind::Ping: return 2; } std::unreachable(); // k always holds one of the three enumerators ``` Without it, a `Kind` made by casting an out-of-range integer would fall off the end of a non-void function, which is also undefined behaviour; `std::unreachable()` states explicitly that this path cannot happen instead of leaving it implicit. Apple clang 21 does not warn about the missing return when the `switch` covers every enumerator. ## The danger: a false promise is undefined behaviour | Facility | Checked at run time? | If the condition is false | Optimizer may use it? | |---|---|---|---| | `assert(expr)` | yes, unless `NDEBUG` is defined | prints a message and calls `std::abort` | not as an assumption | | `[[assume(expr)]]` | never | undefined behaviour | yes | | `std::unreachable()` | never | undefined behaviour when reached | yes | That table is the whole interview answer. An assumption is a promise the compiler believes without checking, so a wrong assumption creates exactly the bugs this branch describes: deleted checks, removed branches, out-of-bounds reads. A `Kind` value read from a corrupt file and cast to the enumeration, or a negative length that "can't happen", turns `std::unreachable()` or `[[assume]]` into silent misbehaviour. Three further rules catch people out: 1. **The expression is never evaluated**, so side effects in it never happen. The draft's example `[[assume(++y == 43)]]; return y;` does not increment `y`, and the compiler may replace the return with `return 42;`. 2. **The expression is still potentially evaluated** for the one-definition rule, so a function it names must be defined somewhere. 3. **Assumptions must be true on every path**, including after future edits; a comment-level invariant that later code breaks becomes undefined behaviour without any change to the assumption itself. ## A sane team pattern - Use `[[assume]]` and `std::unreachable()` only on hot paths where profiling shows the gain, and only for invariants established inside the program, never for values read from input. - Pair each with a debug check, typically through a project macro that expands to `assert(cond)` in debug builds and to `[[assume(cond)]]` in release builds. - Run tests and sanitizers on the debug variant so a false assumption fails loudly before release. - For contracts that should be checked, C++26 contract assertions are the language feature, covered with the C++26 material. ## std::unreachable() or a default branch? For the exhaustive `switch`, three endings are common, and they differ in what a bad value does: | Ending after the `switch` | Bad enumeration value at run time | Cost | |---|---|---| | `std::unreachable();` | undefined behaviour | none; the compiler may drop range checks | | `std::abort();` | the program stops at a known point | a call on a cold path | | `throw std::logic_error{"bad Kind"};` | the caller can handle it | an exception path | Leaving out a `default:` label keeps the compiler's warning about unhandled enumerators useful when a new enumerator is added; the ending after the `switch` then decides what an out-of-range value does. Choose `std::unreachable()` only when no out-of-range value can exist.

  • Why is [[assume(++y == 43)]] a bug even when y really is 42?
    The assumption's expression is never evaluated, so `y` is not incremented, unlike what the code seems to say. If the author relied on the increment, later code sees the old value. The compiler may also replace later uses of `y` with 42. Assumptions should be side-effect-free conditions on existing values.
  • When would you choose std::unreachable() over throwing or aborting in the default branch?
    Only when the impossibility is guaranteed by the program itself, for example every enumerator is handled and values are never cast in from outside, and the branch sits on a measured hot path. Otherwise `std::abort()` or an exception keeps a defined, diagnosable outcome; `std::unreachable()` turns a wrong belief into undefined behaviour.

  • [[assume(x > 0)]] checks the condition at run time like assert.
  • std::unreachable() throws an exception if control ever reaches it.
  • Side effects inside [[assume(...)]] still run, so ++i in it increments i.
  • A compiler must generate faster code whenever an assumption is present.

Assumes C++23, which added [[assume]] and std::unreachable; C++26 rewords a false assumption as runtime-undefined behaviour.