skip to content

Optimizer Assumptions

Compilers assume UB never happens, so they delete an overflow check or a null test that runs too late. Interviewers ask how a debug build passes while the release build breaks.

on this pageshow

explore

questions

6

Why does a C++ compiler at -O2 delete a signed overflow check written as if (x + 1 < x), and how do you write one that survives?

level: seniorimportance: must knowfreq 55%

answer

  1. the check runs after the overflow
  2. signed overflow never happens, legally
  3. x + 1 < x is always false
  4. compare against INT_MAX - b first
  5. __builtin_add_overflow, ckd_add

basics

~20 s

x + 1 < x can only be true after signed overflow, which is undefined, so the compiler may fold it to false. Test before the add, as in x > INT_MAX - 1, or use __builtin_add_overflow or C++26 ckd_add.

solid answer

~40 s

`x + 1 < x` can only be true if `x + 1` overflowed, and signed overflow is **undefined behaviour**, so in every valid execution the comparison is false. An optimizer is entitled to reason that way: Apple clang 21 at `-O2` compiles `bool will_overflow(int x) { return x + 1 < x; }` to `return false`, and a program that printed 1 at `-O0` prints 0 at `-O2`. The fix is to test **before** the operation, so the check never depends on an overflowed value: `b > 0 && a > INT_MAX - b`, and the mirror case against `INT_MIN`. Alternatives are GCC's and Clang's `__builtin_add_overflow`, C++26's `ckd_add` from `<stdckdint.h>` or `std::saturating_add`, or doing the arithmetic in an unsigned or wider type deliberately. `-fwrapv` defines wrapping, at a cost to optimization.

code

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

// Pre-check: decide before adding, so no overflowing add ever runs.
bool add_checked(int a, int b, int* out) {
    if ((b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b))
        return false;
    *out = a + b;
    return true;
}

// GCC and Clang builtin: computes the wrapped result and reports overflow.
bool add_builtin(int a, int b, int* out) {
    return !__builtin_add_overflow(a, b, out);
}

int main() {
    int r = 0;
    std::printf("%d ", add_checked(INT_MAX, 1, &r));
    std::printf("%d ", add_builtin(INT_MAX, 1, &r));
    std::printf("%d %d\n", add_checked(40, 2, &r), r);
}

go deeper

for a junior

Remember that checking for signed overflow after the addition is too late; the test has to happen before the arithmetic.

for a middle

Explain why x + 1 < x is always false for valid inputs and why unsigned wrap tests are different.

for a senior

Write the INT_MAX and INT_MIN pre-checks, name __builtin_add_overflow and the C++26 helpers, and explain why -fwrapv is not a portable answer.

for a principal

Decide how a codebase standardises checked arithmetic at trust boundaries, a helper library versus compiler flags, so overflow guards cannot silently vanish.

## Why the check is dead code A common way to guard an addition is to do it and then look for the tell-tale wrap: ```cpp bool will_overflow(int x) { return x + 1 < x; } // intended: true for INT_MAX if (a + b < a) { /* overflow */ } // intended: catches b > 0 overflow ``` Both depend on signed arithmetic wrapping from `INT_MAX` to `INT_MIN`. The C++ standard says the opposite: if a result is not representable in its type, the behaviour is undefined. So there are only two cases: 1. `x + 1` does not overflow. Then `x + 1` is mathematically greater than `x` and the comparison is false. 2. `x + 1` overflows. Then the program has undefined behaviour and the standard requires nothing. A compiler only has to get case 1 right, and in case 1 the answer is always `false`. Apple clang 21 at `-O2` emits exactly that for `will_overflow`: `mov w0, #0` followed by `ret`. Run with `x == INT_MAX`, the same program printed `1` at `-O0` and `0` at `-O2`; neither output is a defined result. Unsigned arithmetic is different: it is defined modulo 2^N, so `u + 1 < u` for an `unsigned u` is a valid, well-defined wrap test that compilers must keep. ## Checks that survive optimization | Technique | Standard | Notes | |---|---|---| | Pre-check `b > 0 && a > INT_MAX - b` (and `b < 0 && a < INT_MIN - b`) | any | portable; never evaluates an overflowing expression | | `__builtin_add_overflow(a, b, &r)` | GCC and Clang builtin | returns `true` on overflow and stores the wrapped result | | `ckd_add(&r, a, b)` from `<stdckdint.h>` | C++26 | the C23 checked-integer interface, adopted by C++26 | | `std::saturating_add(a, b)` from `<numeric>` | C++26 | clamps to the type's limits instead of reporting | | compute in `long long` or `std::int64_t`, then range-check | any | only works while the wider type cannot overflow | The pre-check compiles to ordinary comparisons: Apple clang 21 keeps both branches of `add_checked` in the example, because nothing in them is undefined. Two version notes. C++26 renamed the saturation functions during standardization: earlier drafts called the function `std::add_sat`, and that is the name the libc++ shipped with Apple clang 21 provides, while the C++26 final draft and newer libc++ headers spell it `std::saturating_add`. And `ckd_add` compiled with Apple clang 21 in `-std=c++2c` mode. ## The same pattern elsewhere The deleted check is one instance of a general rule: **a test that can only be true after undefined behaviour has happened is dead code**. It recurs in other forms: - a loop `for (int i = start; i <= end; ++i)` where `end == INT_MAX`: the compiler may assume `i` never wraps and compute a trip count; - a "did it go negative?" test after multiplying two positive `int` values; - pointer wrap tests such as `p + len < p`, which the lesson on the packet parser examines; - a null test after a dereference; - a byte count computed as `count * sizeof_elem` in `int` and then tested with `if (bytes < 0)`, which tests for a negative result that only overflow could produce. In each case the rewrite follows the same recipe: decide whether the operation is valid **before** performing it, using only values that are already known to be in range. ## Flags that change the rules GCC documents `-fwrapv` as telling the compiler to assume that signed addition, subtraction and multiplication wrap using two's-complement representation. With it, `x + 1 < x` becomes a meaningful test, but the code then relies on a compiler option rather than on C++, and the flag also disables optimizations that rely on non-wrapping counters. The option tables and their costs belong with the compiler toolchain; the portable fix is the pre-check. ## Interview checklist - Say **why** the compiler may delete the check, not just that it does: the check reads the result of an undefined operation. - Show the portable rewrite with both the `INT_MAX` and the `INT_MIN` side. - Mention the builtin or C++26 helpers, naming the standard. - Point out that unsigned wrap tests are legal, and that converting to unsigned **before** the add is a valid technique when the type's range allows it.

  • Is if (u + 1 < u) a valid overflow test for an unsigned int u in C++?
    Yes. Unsigned arithmetic is defined modulo 2^N, so `u + 1` wraps to 0 when `u` is `UINT_MAX`, the comparison is then true, and the compiler must keep it. The deletion only applies to signed types, whose overflow is undefined. Watch for promotion: for `unsigned short` operands the arithmetic happens in `int`.
  • Why not just compile with -fwrapv instead of rewriting the checks?
    `-fwrapv` makes signed overflow wrap for that compiler only, so the code's correctness then depends on a build flag that a new target, a header-only consumer or another compiler may not set. It also gives up optimizations that assume counters do not wrap. A pre-check is portable C++ and costs a comparison.

  • if (x + 1 < x) is a reliable overflow check because int is two's complement.
  • The compiler deleting the check is an optimizer bug that -O0 avoids.
  • Unsigned wrap tests such as u + 1 < u are deleted the same way.
  • Storing the sum in a long long afterwards makes the overflow check safe.
  • Adding volatile to x stops the overflow from being undefined.

Assumes C++23 for the overflow rule; ckd_add in <stdckdint.h> and std::saturating_add are C++26 additions.

open as a page

Why can a C++ program with undefined behaviour work in a -O0 debug build yet misbehave in a -O2 release build?

level: juniorimportance: should knowfreq 60%

basics

~20 s

Undefined behaviour imposes no requirements, so the optimizer may assume it never happens. At -O0 the compiler translates each statement almost literally and the bug often stays hidden; at -O2 transformations built on that assumption expose it.

open as a page

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%

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.

open as a page

In C++, why can the optimizer remove an if (p == nullptr) check that comes after p->length has already been read?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Reading p->length is undefined if p is null, so after that read the compiler may assume p is not null and delete the later p == nullptr test as dead code. Put the null check before the first dereference.

open as a page

A C++ packet parser checks if (p + len < p || p + len > end) before reading a field, yet the release build skips the wrap-around test; why, and what is the fix?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Forming p + len beyond one past the end of the buffer is already undefined, so the compiler may assume p + len never wraps and fold p + len < p to false. Compare lengths instead: len > static_caststd::size_t(end - p).

open as a page

In C++, how can undefined behaviour later in a function change what code before it does, and how do C++26 observable checkpoints limit that?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

Up to C++23, an execution that will hit undefined behaviour has no requirements at all, even for operations before it, so a compiler may reshape earlier code. C++26 protects only what precedes an observable checkpoint, such as a returned stdio write or std::observable_checkpoint().

open as a page