3 ms·
Really? Isn't is still the case that signed integer arithmetic can lead to UB? Despite this, there's a push for Almost Always Int from the C++ powers-that-be.
by dirtydroog 7y ago
Really? Isn't is still the case that signed integer arithmetic can lead to UB? Despite this, there's a push for Almost Always Int from the C++ powers-that-be.
https://stackoverflow.com/questions/16188263/is-signed-integer-overflow-still-undefined-behavior-in-c https://stackoverflow.com/questions/16188263/is-signed-integ...
- shakna 7y agoC++20 specifies two's complement for signed integer arithmetic, like it was already for unsigned, which means most (basically everything except -INT_MIN) is now no longer UB. [0] http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0907r4.html http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p090...
- gpderetta 7y agoI believe the representation is no longer implementation defined, but signed overflow is still UB.
- tomnj 7y agoThat’s correct, and it’s quoted in JF’s paper linked above: “ The main change between [P0907r0] and the subsequent revision is to maintain undefined behavior when signed integer overflow occurs, instead of defining wrapping behavior.”
- pingyong 7y ago>Status-quo If a signed operation would naturally produce a value that is not within the range of the result type, the behavior is undefined. The author had hoped to make this well-defined as wrapping (the operations produce the same value bits as for the corresponding unsigned type), but WG21 had strong resistance against this. I really don't understand why WG21 is against this, do you happen to have a link to arguments against it? The only one I frequently see is that "it's faster that way" with a link to godbolt where iterating with a 32-bit signed integer on a 64-bit system is faster than iterating with a 32-bit unsigned integer, because the compiler exploits UB here to ignore overflow. Which is of course a completely useless example because simply using a correctly sized integer for iteration, signed or unsigned, will always result in the fastest most correct code. I'm not aware of any other arguments against it.
- gpderetta 7y agoWith signed iterator variables, the compiler can more easily infer that the loop will not wrap around and allows better code motion and vectorization.
- tomnj 7y agoAt least in the case of overflow, the article mentions a few arguments: “”” This direction was motivated by: Performance concerns, whereby defining the behavior prevents optimizers from assuming that overflow never occurs; Implementation leeway for tools such as sanitizers; Data from Google suggesting that over 90% of all overflow is a bug, and defining wrapping behavior would not have solved the bug. “””