Does “Undefined Behavior” really permit *anything* to happen? [duplicate]

Yes, it permits anything to happen. The note is just giving examples. The definition is pretty clear:

Undefined behavior: behavior for which this International Standard imposes no requirements.


Frequent point of confusion:

You should understand that “no requirement” also means means the implementation is NOT required to leave the behavior undefined or do something bizarre/nondeterministic!

The implementation is perfectly allowed by the C++ standard to document some sane behavior and behave accordingly.1 So, if your compiler claims to wrap around on signed overflow, logic (sanity?) would dictate that you’re welcome to rely on that behavior on that compiler. Just don’t expect another compiler to behave the same way if it doesn’t claim to.

1Heck, it’s even allowed to document one thing and do another. That’d be stupid, and it’d probably make you toss it into the trash—why would you trust a compiler whose documentation lies to you?—but it’s not against the C++ standard.

Leave a Comment