constexpr catches undefined behavior at compile time and nowhere else
After the hardened standard library post, a reader, Zamfir Yonchev, commented. He wrote: “I wish there was a language construct for enabling checking of UB of this kind on a per-statement basis”. (The link opened without a login when we fetched it on 2026-10-07.) This series takes that question one case at a time. The first tool is the one the language already has: evaluate the code in a constant expression and let the compiler refuse undefined behavior.
In short
- Put the checks in a compile-time test suite, and the compiler rejects an out-of-range index, signed overflow, division by zero and a null dereference. GCC 16.2 and Clang 23.1 each rejected all six bad calls we tried.
- The standard requires the compiler to reject overflow, division by zero and a null dereference. For an out-of-range index it leaves the choice to the implementation, and libstdc++ diagnoses it.
- The same calls with run-time values compile without a warning. At
-O2they exit 0 and print stale values. - The check sees only the values written into the test, not the input a user types at run time.
- Not tested: the MSVC STL, and the precondition checks of libc++ itself.
One suite, six bad calls
The file defines small constexpr functions for the cases and a static_assert suite over them:
constexpr int array_at(std::size_t i) {
std::array<int, 3> a{10, 20, 30};
return a[i];
}
constexpr int add_one(int x) { return x + 1; }
constexpr int divide(int a, int b) { return a / b; }
constexpr int deref(const int* p) { return *p; }
static_assert(array_at(2) == 30);
static_assert(add_one(41) == 42);
static_assert(divide(84, 2) == 42);
The functions vector_at and span_at follow the same shape. Built as it stands, every assertion holds. Compiling with -DCASE=N, for N from 1 to 6, adds one more static_assert that makes a single bad call. The six calls are the rows of the table below, and each one stops the build.
GCC 16.2 (-std=c++26 -Wall -Wextra) says, after non-constant condition for static assertion:
| call | GCC 16.2 error |
|---|---|
array_at(3) |
call to non-'constexpr' function 'void std::__glibcxx_assert_fail(const char*, int, const char*, const char*)' at array:210 |
vector_at(3) |
the same text, at stl_vector.h:1253 |
span_at(3) |
the same text, at span:288 |
add_one(INT_MAX) |
overflow in constant expression [-fpermissive] |
divide(1, 0) |
'(1 / 0)' is not a constant expression |
deref(nullptr) |
dereferencing a null pointer |
Clang 23.1 on Compiler Explorer rejects the same six calls. Its error reads static assertion expression is not an integral constant expression. For the last three calls, its notes read:
- signed overflow:
value 2147483648 is outside the range of representable values of type 'int' - division by zero:
division by zero - null dereference:
dereferencing a null pointer is not allowed in a constant expression
The build with -stdlib=libc++ rejects them too. These runs were on Compiler Explorer, so Clang used its bundled libstdc++ 15.2 in the default mode.
Where the rule comes from
The standard lists what stops an expression from being a core constant expression ([expr.const], paragraph 2 in the current draft, fetched 2026-10-07). One item is “an operation that would have undefined or erroneous behavior as specified in Clause [intro] through Clause [cpp]”. Signed overflow, division by zero and a null dereference are defined in those clauses, so a conforming compiler has to reject them.
An out-of-range operator[] is different. Its precondition is written in the library clauses, and paragraph 4 says it is unspecified whether such an expression is a core constant expression. So whether v[3] on a three-element vector is diagnosed is up to the implementation. libstdc++ chooses to diagnose it. Its c++config.h says that without _GLIBCXX_ASSERTIONS the assertion checks are enabled only during constant evaluation, “to diagnose undefined behaviour in constant expressions”. We built at -O2 with the macro defined and with it left out. GCC rejected all three index cases both times. The error text differs: __glibcxx_assert_fail() takes no arguments in the constant-evaluation-only version.
With libc++, Clang’s notes name a different reason. For an index of 3 it reads read of dereferenced one-past-the-end pointer is not allowed in a constant expression, and for 100 it reads cannot refer to element 100 of array of 3 elements in a constant expression. Those are core-language rules about the array, not a libc++ assertion. So this test does not show whether libc++ checks the precondition itself in constant evaluation.
The same functions at run time
Nothing in the file changed except where the argument comes from. main passes values derived from argc, so the compiler sees no constant:
It compiles without a warning and exits 0. On Compiler Explorer, the array and span calls at index 3 printed 0 in one run and 32766 in another with the same binary settings. The vector call at index 3 printed 0. Clang 23.1 -O2 printed 990059265 for the array and span reads. The expression add_one(INT_MAX) > INT_MAX printed true. A wrapped addition cannot produce that, because the optimizer is allowed to assume the addition does not overflow.
Exit codes and output for the whole matrix, measured on Compiler Explorer (x86-64) with the default run and the div and null arguments:
| compiler and flags | index and overflow | divide(1, 0) |
deref(nullptr) |
|---|---|---|---|
GCC 16.2 -O0 |
exit 134, array:210 ... Assertion '__n < this->size()' failed. |
SIGFPE | SIGSEGV |
GCC 16.2 -O2 |
exit 0, stale values | exit 0, printed 0 |
SIGSEGV |
GCC 16.2 -O2 -D_GLIBCXX_ASSERTIONS |
exit 134, same assertion | not run | not run |
Clang 23.1 -O0 |
exit 134, same assertion | SIGFPE | SIGSEGV |
Clang 23.1 -O2 |
exit 0, stale values | exit 0, printed 0 |
exit 0, printed 2 |
The -O0 rows are the hardened standard library’s checks from the earlier post, on by default in an unoptimized libstdc++ build. Run time behavior is the territory of the hardened library and of the sanitizers.
What constexpr covers
The check happens when a constant expression is evaluated. It sees the values you wrote into the test. That makes it a way to turn a test suite into a compile-time proof for those inputs. It does not look at the index a user types at run time. It does not mark code that was never written as a test. A function has to be constexpr for a static_assert to call it, and every function it calls has to be too.
Trail of Bits published constexpr-everything, a libclang tool that rewrites code to add constexpr wherever it can be evaluated. The repository is archived, its last commit is from 2022-03-01, and its README says it requires LLVM 9, 10 or 11. We did not run it.
What this has not been tested on
- MSVC STL: not compiled. We do not know whether it diagnoses an out-of-range
operator[]in constant evaluation. - libc++’s own precondition checks in constant evaluation: not isolated. The Clang runs with libc++ were rejected by core-language rules.
- GCC and Clang only on Compiler Explorer (x86-64). The GCC 16.2 Docker image was used for the standard library header text and the
-O2macro matrix. On its aarch64 build,divide(1, 0)at run time returned0instead of raising SIGFPE. - Clang with its own libc++ at versions other than 23.1, and any version of GCC other than 16.2.
- constexpr-everything: not run.
The examples are in cpp26-reflection-examples under posts/89-constexpr-catches-ub.
Sources:
- expr.const in the C++ working draft (draft commit c7015b4, fetched 2026-10-07) for paragraphs 2 and 4.
- libstdc++
bits/c++config.has installed with GCC 16.2 for the assertion macros. - trailofbits/constexpr-everything for the archive status, the last commit date and the LLVM versions.
- Compiler diagnostics and exit codes were measured on Compiler Explorer with
g162andclang2310. The matrix was run once, and the stale values differ between runs.