K
Keith Thompson
Joe Pfeiffer said:Well, yes there is. For example on an addition, if both operands have
the same sign and the result is the other sign, you had an overflow.
Analogous conditions exist (which I don't remember off the top of my
head and am too lazy to look up) exist for subtraction and
multiplication. Integer division can't overflow.
On many systems, yes, you can detect signed overflow after the fact by
examining the values of the operands and the result. But in C, the
behavior is undefined -- and even on systems that use 2's-complement, an
optimizing compiler can take advantage of that fact and generate code
based on the assumption that overflow never occurs. For example, this:
int x = INT_MAX;
if (x + 1 < x) {
fprintf(stderr, "Overflow!\n");
}
can be optimized away (For example, gcc does this at -O2 and above.)
And yes, integer division can overflow; consider INT_MIN / -1.
My reading of the question was "OK, you've detected an overflow. Now
what do you do about it?" and the (correct) answer was, in essence,
"well, what do you *want* to do about it?"
But detecting the overflow in the first place can be *very* tricky.