hgm wrote:Rein Halbersma wrote:The reason that some program constructs in C lead to undefined behavior is that the mapping of C to hardware is not one-to-one. Some things cannot be defined in a portable way because of the enormous diversity in hardware (memory models, bus-width, cache coherence etc.).
Yes, I understand that. And that is OK with me. But what is not OK with me is that that it should be allowed to use this as an excuse to dream up other responses than any existing or conceivable hardware would ever exhibit. UB is supposed to stand for undefined behavior, not for undesired behavior!
I agree with this, and so do many people on the C++ Committee . It was linked here before, but here it goes again: the mailinglist for the C++ Study Group on Undefined Behavior (it is likely that their insights will also be closely followed by the C Committee)
http://www.open-std.org/pipermail/ub/
This study group is not a conspiracy of malicious or naive people trying to frame veteran programmers by breaking their seasoned code. If you read their posts, I think you'll get more appreciation for the tradeoffs that language designers and compiler writers are facing. Some quotes:
On the signed integer overflow debacle
Signed integer overflow is a fairly good example here, I believe:
(1) Is a compiler diagnostic acceptable? Yes.
(2) Is a run-time abort acceptable? Yes.
(3) Is an unspecified result value acceptable? Yes.
(4) Is it acceptable that your compiler changes the behavior
of unrelated code that follows the overflow? That's very surprising.
Giving compilers latitude to choose among 1-3 (depending on the
target audience) is fine, but, in my opinion, prohibiting option 4
would be an improvement.
On the performance benefits of assuming no UB is present
Consider a program that adds a constant to a signed integer
in a loop. Under the current model, the compiler can assume
that the variable is monotonically increasing, and can therefore
eliminate comparisons, which leads to simpler loops, which leads
to vectorization, which leads to implementation in GPUs, ....
Without that assumption, the chain of optimizations disappears.
On winning the hearts and minds of programmers
I am hoping SG12's recommendations and resolutions will be more than
just "educate programmers on undefined behavior". We have been educating
C++ programmers for more than 25 years about these issues, and I am not
quite sure we can categorically say we have won on this front -- in
fact, I think we haven't and we are not winning -- and if we did, we
haven't done it at the pace of sophistication of optimizers.