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();
}
[Edit]
Answer: Combining @Gareth Rees answer with some other ideas resulted in:
#include <limits.h>
int safe_add(int a, int b) {
if (a >= 0) {
if (b > INT_MAX - a) {
; /* handle overflow */
}
} else {
if (b < INT_MIN - a) {
; /* handle underflow */
}
}
return a + b;
}
Note: Solution does not require 2's complement.
Note: This post does not address unsigned
overflow.
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