I can understand leaving something implementation defined, so that the particular people implementing it would know what's best to happen, but why would something ever be undefined behavior? Why not just say, anything else is implementation defined?
Undefined behavior exists mainly to give the compiler freedom to optimize. One thing it allows the compiler to do, for example, is to operate under the assumption that certain things can't happen (without having to first prove that they can't happen, which would often be very difficult or impossible).
Undefined behavior contributes to many serious problems, including security vulnerabilities. It's also, I believe, poorly understood, and discussions of it tend to become contentious.
C and C++ have undefined behavior, because nobody's defined an acceptable alternative that allows them to do what they're intended to do. C# and Java take a different approach, but that approach fits poorly (if at all) with the goals of C and C++.
In computer programming, undefined behaviour is defined as 'the result of compiling computer code which is not prescribed by the specs of the programming language in which it is written'.
There are a lot of cases in which ensuring an implementation defined behavior inevitably incurs overhead.
For example, how to make buffer overflow an implementation defined behavior? Maybe throw exception when it's detected, or maybe terminate the program? But doing that always requires bounds-checking.
C++ is designed in such a way that performance is almost never compromised.
There are languages like Go, Rust, and Java which do bounds-checking. And they all incur overhead to pay the price for the safety.
Language specifications can be seen as a contract between the compiler writers and programmers. There are things that programmers assume that compiler would do (and not do). Compiler writers assume few things a programmer would do.
Compiler writer assumes programmer would write the code that has documented behavior or is free from undefined behavior. Based on that compiler writers can ignore some constructs and can make the compiled program faster as compared to the case if those constructs were not undefined. Some of such (as much as possible) undefined constructs are documented in the specifications to give the programmers an idea of such constructs.
Such undefined behavior exist to reduce the unnecessary complexity in implementation of specifications and sometimes to leave rooms for optimization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With