'Why is Signed Overflow due to computation still Undefined Behavior in C++20
I came to know through this answer that:
Signed overflow due to computation is still undefined behavior in C++20 while Signed overflow due to conversion is well defined in C++20(which was implementation defined for Pre-C++20).
And this change in the signed overflow due to conversion is because that from C++20 compilers are required use 2's complement.
My question is:
If compilers are required to use 2's complement from C++20, then why isn't signed overflow due to computation well-defined just like for signed overflow due to conversion?
That is, why(how) is there a difference between overflow due to computation and overflow due to conversion. Essentially, why these two kinds of overflows treated differently.
Solution 1:[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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | eerorika |