""Why is this UB not caught during constexpr execution? #include <cstdint> consteval…
- User
""Why is this UB not caught during constexpr execution?
#include
consteval std::int8_t f(std::int8_t value) { for(int i = 0; i < 1000; ++i) { value -= 1; } return value; }
static_assert(f(0) == 24);""
Assistant
This is a great question about constexpr evaluation and undefined behavior detection!
The code has undefined behavior due to signed integer overflow when
value(anint8_t) underflows below -128. However, thestatic_assertpasses because signed integer overflow during constant evaluation is not required to be diagnosed by the C++ standard.Here's what's happening:
-
The UB occurs: Starting from 0, subtracting 1 a thousand times causes the
int8_tto underflow multiple times (it wraps from -128 to 127 due to two's complement representation on most platforms). -
Why it's not caught: The C++ standard distinguishes between:
- Required diagnostics: Things like dereferencing null pointers, out-of-bounds array access
- Optional diagnostics: Signed integer overflow
Signed integer overflow is explicitly undefined behavior ([expr.pre]/4), but compilers are not required to diagnose it during constant evaluation.
-
Implementation behavior: Most compilers (GCC, Clang, MSVC) use two's complement wrapping behavior even in constexpr contexts, which is why you get a consistent result of 24:
- 0 → -1 → ... → -128 → 127 → 126 → ... (cycles through 256 values)
- After 1000 iterations: 0 - 1000 ≡ 24 (mod 256)
To catch this UB, you could:
- Use
-fsanitize=undefinedat runtime (won't help with constexpr) - Use unsigned types (wrapping is well-defined for unsigned)
- Add explicit bounds checking:
consteval std::int8_t f(std::int8_t value) { for(int i = 0; i < 1000; ++i) { if (value == std::numeric_limits<std::int8_t>::min()) throw "overflow!"; // This WOULD cause a compile error value -= 1; } return value; }The key insight is that constexpr evaluation doesn't guarantee catching all UB - only certain categories that the standard mandates must be diagnosed.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.