I have got two signed integers, and I would like to subtract them. I need to know if it overflowed.
int one;
int two;
int result = two - one;
if (OVERFLOW) {
printf("overflow");
} else {
printf("no overflow");
}
Something like that. Is there a good way to do this?
Firstly, overflow in signed calculations causes undefined behavior in C.
Secondly, forgetting about UB for a second and sticking to the typical overflow behavior of a 2’s complement machine: overflow is revealed by the fact that result “moves” in the “wrong direction” from the first operand, i.e when the result ends up greater than the first operand with positive second operand (or smaller than the first operand with negative second operand).
In your case