Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-opus-4-1-20250805· AnthropicHugging Face Arena Expert 5K

""Why is this UB not caught during constexpr execution? #include <cstdint> consteval…

  1. 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);""

  2. Claude 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 (an int8_t) underflows below -128. However, the static_assert passes because signed integer overflow during constant evaluation is not required to be diagnosed by the C++ standard.

    Here's what's happening:

    1. The UB occurs: Starting from 0, subtracting 1 a thousand times causes the int8_t to underflow multiple times (it wraps from -128 to 127 due to two's complement representation on most platforms).

    2. 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.

    3. 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:

    1. Use -fsanitize=undefined at runtime (won't help with constexpr)
    2. Use unsigned types (wrapping is well-defined for unsigned)
    3. 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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.