I was reading about techniques to detect overflow in C . one of the examples to show incorrect solution to detect overflow in addition was this one :
/* Determine whether arguments can be added without overflow */
int tadd_ok(int x, int y) {
int sum = x+y;
return (sum-x == y) && (sum-y == x);
}
and it said it doesn’t work because :
two’s-complement addition forms an abelian group, and so the
expression (x+y)-x will evaluate to y regardless of whether or not the
addition overflows, and that (x+y)-y will always evaluate to x
What does it exactly mean ? Does it mean that C compiler replace sum with x+y ?
To figure out what is it saying I even traced assembly code of the program, but there was no sign of replacement .
Update : The essence of my question is, does GCC evaluates an expression without calculating it ?
This is NOT a question about two’s complement.
You can see a sample output in here .
If you take a trivial example of
4 (0b0100) + 5 (0b0101)you can see that the unsigned sum should be9 (1001)which is actually-7in two’s complement. If you then take that sum (0b1001) and subtract 4 from it using two’s complement arithmetic:you end up with 0101 which is 5 (you drop the overflowing most significant 1 during a 2’s complement operation). Subtracting 5 from the sum equals 4:
This satisfies the c code you provided but still resulted in an overflow.
From wikipedia’s article on two’s complement:
Update:
To demonstrate your INT_MAX example using my trivial 4 bit integer system with INT_MAX = 7 we can see the same result as your c code.
Just like my example above, subtracting,
sum - 7will equal7.