ub-checks-per-statement
Part of the wro.cpp ub-checks-per-statement series — 4 of 4 posts published so far.
constexpr catches undefined behavior at compile time and nowhere else
A static_assert over a constexpr test suite stops the build on an out-of-range std::array, std::vector or std::span index, signed overflow, division by zero and a null dereference. GCC 16.2 and Clang 23.1 each reject all six bad calls we tried. The same functions called with a run-time value compile cleanly and, at -O2, print stale memory or return a value no wrapped add could produce. Episode 1 of the UB checks per statement series.
contract_assert checks one statement, and a build flag decides what a failure does
A contract_assert placed in front of a vector access is a per-statement bounds check in C++26. On GCC 16.2 the same source ignores, reports, or terminates depending on -fcontract-evaluation-semantic, so a debug and a release build differ by one flag. libstdc++'s _GLIBCXX_ASSERTIONS is a separate mechanism that never calls the contract violation handler.
Handling overflow and division by zero without undefined behavior
INT_MAX + 1 and x / 0 are undefined for int, and the tools that remove the undefined behavior apply three different policies: std::saturating_add clamps the result, ckd_add reports and leaves the decision to the caller, and -ftrapv or UBSan with -fsanitize-trap stops the program. A table of what each does on GCC 16.2, with the exact diagnostics, including the build where -ftrapv does not trap.
Which checking tool catches which undefined behavior
Seven undefined statements (vector and array index, signed overflow, integer division by zero, null pointer and null unique_ptr dereference, uninitialised read) run under seven checking mechanisms on GCC 16.2: constexpr, contract_assert, _GLIBCXX_ASSERTIONS, UBSan, ASan, -ftrapv and C++26 erroneous behavior. One table of which mechanism stops, which only reports, and which says nothing. No mechanism covers every row, and none of them is an operator on a single expression.