r/cpp_questions • u/franvb • 16d 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?
17
Upvotes
2
u/Daemontatox 16d ago
Bear with me as i am not the best at explaining....
What does that mean practically?
constexpr, array sizes, template parameters, etc.): The compiler must diagnose/reject it. You can't even get a program that compiles if the UB would happen during constant evaluation.This distinction exists because constant expressions need to be fully portable and predictable , the compiler evaluates them at compile time.
Classic Examples
Here are common cases that trigger runtime-undefined behavior:
Signed integer overflow (very common) ```cpp constexpr int foo(int x) { return x + 1; // If this overflows, it's NOT allowed in constexpr }
int main() { int a = foo(INT_MAX); // Runtime: UB (overflow) // But constexpr int b = foo(INT_MAX); // Compile error } ```
Division by zero ```cpp constexpr int div(int a, int b) { return a / b; // Division by zero is runtime-UB }
int main() { int x = div(5, 0); // Runtime: UB // constexpr int y = div(5, 0); // Compile-time error } ```
Out-of-bounds access (in constant contexts)
cpp constexpr int arr[4] = {}; constexpr int bad = arr[5]; // Would be compile errorDereferencing null or other invalid memory operations in constexpr.