This code is invalid.
Assuming the usual rules of the 2nd complement for bitwise XOR for signed integers, then
(s^a) < 0
- this is the case if s and a have signed bits set to opposite values. Thus,
((s^a) < 0 && (s^b) < 0)
indicates that s has a sign different from both a and b , which should have an equal sign (pretending to be 0 is positive). If you add two equal signs and get the result of a different sign, there must be an overflow, so this is an overflow check.
If we assume that the signed overflow wrappers, then s has the opposite sign from a and b exactly when the overflow occurred. However, the signed overflow is undefined. The calculation of s already incorrect; we need to check if an overflow will occur without actually performing the operation.
Python should not do this. You can see what it should do in the Python 2 source code for int.__add__ :
x = (long)((unsigned long)a + b); if ((x^a) >= 0 || (x^b) >= 0)
It is assumed that it must distinguish between unsigned in order to obtain certain overflow behavior. The cast-to-unsigned fix was introduced in 5 different places as a result of issue 7406 in Python, but it looks like they missed since then the location has changed, or perhaps INPLACE_ADD . I left a message on the tracker.
user2357112
source share