logoalt Hacker News

cataphracttoday at 5:31 PM1 replyview on HN

Undefined behavior is not the same as implementation-defined or unspecified behavior. A program with undefined behavior is by definition an incorrect program. But there are cases where the spec actually gives some margin to the implementation. Programs relying on the choices of the implementation may be correct, even if non-portable.


Replies

Maxatartoday at 6:23 PM

>A program with undefined behavior is by definition an incorrect program.

This is simply false and an oft repeated myth. Undefined behavior has a specific technical definition that is in the C++ standard [1] and there is absolutely no mention in that definition or the implication of that definition that undefined behavior necessarily results in an invalid or incorrect program.

The definition of undefined behavior, right from the standard itself is... and I quote... get ready for it...

"behavior for which this document imposes no requirements"

That's it, nothing more, nothing less.

The standard even goes out of its way to state the following:

"Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, *to behaving during translation or program execution in a documented manner* characteristic of the environment".

Behaving in a documented manner characteristic of an environment is a far cry from being by incorrect by definition.

[1] https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/n49...

show 4 replies