2 ms·
AFAICT, the main rationale for undefined behavior in the original instance boils down to traps: any operation that could trap is undefined. In particular, this
by jcranmer 9y ago
AFAICT, the main rationale for undefined behavior in the original instance boils down to traps: any operation that could trap is undefined. In particular, this seems to motivate why signed integer overflow is undefined as opposed to implementation-defined. It should be pretty clear why it's a good thing that potentially-trapping instructions have undefined semantics in those instances (or, perhaps more accurately, have semantics that have large leeway for when, where, and if the trap is triggered).
Undefined behavior is generally nowhere near as bad in practice as it's often made out to be in practice. It's mostly a case of taking code that is manifestly wrong and making it manifest wrongly in different ways, and when you look at how and why compilers use the undefined behavior to optimize, it's hard to actually object to it. The two main counterexamples are strict aliasing (although it should be noted that most compilers will use the strict aliasing rules only if it failed to figure out aliasing by other means, so trivial things like int_var = (int)&float_var don't end up being deleted as being nonsensical) and signed integer overflow (note that wraparound semantics usually are as equally bad as undefined behavior, but making it be undefined makes it challenging to check if the operation would overflow).
- leeter 9y agoNot just traps... systems level code often relies on what is by the standard "Undefined Behavior" but is in fact well defined for that implementation, something the standard allows for very good reason. At the end of the day interacting with hardware sometimes requires doing things that "No Sane Programmer" would ever do normally. Most of undefined behavior is a nice way to say that the standard is not going to try to define something that is probably an artifact of the implementation. Compiler writers can however use and abuse the fact that there is no constraints. MSVC will prune code with undefined behavior. Clang may call the never-called (only if not static or in an anonymous namespace), etc. Undefined behavior is only undefined by the standard... in most cases it has very well defined results.. for a specific implementation and hardware set.