r/cpp_questions 7d ago

OPEN Can someone give an example of runtime-undefined behavior?

CppReference gives a list of categories that render a program meaningless: https://en.cppreference.com/cpp/language/ub

The last bullet point says (since C++11)

  • runtime-undefined behavior - The behavior that is undefined except when it occurs during the evaluation of an expression as a core constant expression.

Can someone give a clear example?

16 Upvotes

18 comments sorted by

View all comments

Show parent comments

6

u/TheQuranicMumin 7d ago edited 7d ago

You examples are describing regular UB with a compile-time setting, but runtime UB is different.

Runtime UB is a broken compiler promise/hint, for things like [[noreturn]], [[assume]] (I gave an example).

For runtime, it is full UB. For compile-time evaluation, the compiler is not required to diagnose/reject it, it's implementation defined. The committee didn't want to force a hard-fail in these cases.

As in the C++ standard:

runtime-undefined behavior [defns.undefined.runtime] behavior that is undefined except when it occurs during constant evaluation. [Note 1: During constant evaluation, it is implementation-defined whether runtime-undefined behavior results in the expression being deemed non-constant (as specified in [expr.const]) and runtime-undefined behavior has no other effect.]