C++ › Undefined Behavior

What is undefined behavior (UB) in C++?

Beginner

Answer

Undefined behavior is program behavior the C++ standard places no requirements on—anything can happen: a crash, wrong results, or seemingly working code that breaks later or under optimization. The compiler may assume UB never occurs and optimize accordingly. UB arises from invalid operations like out-of-bounds access, use-after-free, or signed overflow.
int a[3]; a[5] = 1;   // out-of-bounds: undefined behavior
Real-world example Code that 'worked' in debug crashes in release because the optimizer exploited an assumption of no UB.

Common follow-ups: Can the compiler assume UB never happens? | Give an example of UB.