Why is Signed Overflow due to computation still Undefined Behavior in C++20
Solution 1:
If non-two's-complement support had been the only concern, then signed arithmetic overflow could have been defined as having implementation defined result, just like converting an integer has been defined. There are reasons why it is UB instead, and those reasons haven't changed, nor have the rules of signed arithmetic overflow changed.
In case of any UB, there are essentially two primary reasons for it to exist:
- Portability. Different systems behave in different ways and UB allows supporting all systems in an optimal way. In this case as Martin Rosenau mentions in a comment, there are systems that don't simply produce a "wrong" value.
- Optimisation. UB allows a compiler to assume that it doesn't happen, which allows for optimisations based on that assumption. Jarod42 shows an example in a comment. Another example is that with UB overflow, it is possible to deduce that adding two positive numbers never produces a negative number, nor a number that is smaller than either of the positive numbers.