marss said:
[...]
int var1 = 2000000000;
int var2 = -2000000001;
var1 -= var2; //-294967295 = result is truncated
var2 += var1; //2000000000
var1 = var2 - var1; //-2000000001
Why this happens?
Well, first, the result isn't "truncated". It overflowed.
As for why it works okay, it's because the overflow isn't actually a
problem unless you care about the intermediate value. And in this case
you don't. All that you lose in the overflow is the bit that would have
been carried; all of the other bits are just as they should be. And the
carry bit isn't required for the subsequent operations that restore the
original value to wind up correct (you get more overflow, and again the
carry bit is irrelevant).
Another way of looking at it is that you've got a bit circular number
line, where the circle connects at the minimum and maximum values for
the type. The addition and subtraction operations shift your position
around on the number line and may in fact cross that place on the number
line where the min and max meet, but wrapping around doesn't hurt, as it
simply gets offset in the subsequent operation back into the correct
range of values.
As long as you're dealing with a type that allows this overflow to occur
undetected and uncorrected, there's no problem.
Pete