Hacker News new | ask | show | jobs
by leni536 1168 days ago
Per standard wording if an evaluation contains an undefined operation then it is not a constant expression. It means that undefined behavior should result in compilation failure if it happens in a context where a constant expression is required, like in static_assert.

However the standard only requires this for language-level undefined behavior. For undefined behavior happening in the standard library it's unspecified whether the expression is a constant expression or not. So no, constexpr tests don't cover all possible UB.

Also even if in theory language-level undefined behavior should be caught in constant expressions, in practice compilers miss a number of undefined behaviors. They are generally good at catching out-of-range indexing, using objects outside of their lifetime, using uninitialized values, signed integer overflow and modifying const objects. However there are a number of subtle undefined behaviors that they don't catch, like unsequenced operations on the same object, invalid values for unscoped enums.

There might be some overlap with runtime tests with -fsanitize=undefined,address. For catching uninitialized values at runtime though you probably need msan, which is a pain to set up, but constexpr tests cover that. On the other hand the function you test might not be available at compile-time.

Anyway, constexpr tests are a valuable tool. It's not a silver bullet.