I was reading about why the following code is buggy:
int tadd_ok ( int x, int y ) {
int sum = x + y;
return ( sum - x == y ) && ( sum - y == x );
}
The explanation was that two's complement addition forms an abelian group and so the expression
(x + y) - x
with evaluate to y
regardless if whether or not the addition overflows.
(Same for (x + y) - y)
which will evaluate to x
).
I don't understand this explanation or the abelian group reference. Two's complement addition is basically unsigned modulo arithmetic that is "converted" to two's complement, right?
So for example if we have 4 bits we have the range [-8, 7].
In the example if we had x = 7
and y = 6
the result overflows to 6. And that is not equal to either y
or x
.
So why is the explanation that the equality is always valid regardless of the overflow?