On Tue, 12 Jun 2007 14:27:03 +0100, Mike Aubury
<mi*********@aubit.comwrote in comp.lang.c:
Is there any standard (or even non-standard) way to detect limit overflow in
arithmetic in C ?
eg.
/* assuming 4 byte ints.. */
int a=2147483647;
int b=2147483647;
int c;
c=a*b;
No, there is not. If the result of an arithmetic operation on signed
integer or floating point types is outside the range of the type, the
result is undefined behavior. If an arithmetic operation on unsigned
integer types overflows or underflows, the behavior is well-defined,
but no indication is possible.
If it is important, you need to check before you perform the
operation.
Here is a quick snippet for adding two positive signed ints:
#include <limits.h>
/* ... */
if ((INT_MAX - a) b)
{
c = a + b;
}
else
{
/* overflow handler */
}
/* ... */
There are various cases for addition and subtraction. For addition,
an overflow can only occur when the two values have the same sign. For
subtraction, it can only occur when they have opposite signs.
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://c-faq.com/
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html