3 ms·
There are a few reasons to make things UB. One of the big reasons is--drumroll--to enable compiler optimizations. The other big reason is some variation on the
by jcranmer 4y ago
There are a few reasons to make things UB. One of the big reasons is--drumroll--to enable compiler optimizations. The other big reason is some variation on the problem that actually coming up with reasonable semantics is difficult to impossible, and often one of the factors that makes such semantics difficult is again because of compiler optimizations.
I think there's a big misconception here that the use of UB to drive optimizations is somehow a perversion of the original design for C, but the evidence strongly points away from that. In particular, strict aliasing rules don't really make sense unless you're going to use them to afford optimization opportunities, and those were present as far back as C89.
I will additionally point out that any C-like language is going to have a large kernel of necessarily UB to permit any optimization whatsoever (namely, UB in relation to memory unsafety) [1]. The things in C where people most complain about UB--namely signed integer overflow and strict aliasing--also happen to be the ones where there's no good reason to interpret C89's decision to make them UB instead of something lesser as anything other than letting compilers optimize them because they're UB. Even if it seems to be gratuitous (and I would personally argue that it is), it is very much intentional.
[1] Yes, even Rust makes this UB.