To detect int
overflow/underflow in C, I use the below code.
What might be simpler and portable code? (that is: fewer tests)
Assume 2's complement and don't use wider integers.
int a,b,sum;
sum = a + b;
// out-of-range only possible when the signs are the same.
if ((a < 0) == (b < 0)) {
if (a < 0) {
// Underflow here means the result is excessively negative.
if (sum > b) UnderflowDetected();
}
else {
if (sum < b) OverflowDetected();
}
float
can represent is0.001
.1.0 / 10000
would result in a value of0.0
because the actual value is too small. – Fiddling Bits Dec 12 '13 at 0:44int
s by employingunsigned
conversion? OTOH if you are talking about overflow detection for 2unsigned
, that is a different question.if (sum < a) OverflowDetected();
seems to work for that. – chux Dec 12 '13 at 15:46