How to Avoid Integer overflow in C?

Here is the General Way to avoid integer overflow
Example 1
value = value + 100;
if ULONG_MAX – 100 >= value
then No Overflow
else
overflowed
Example 2
x = x * 10 + r;
To Check whether x would overflow, do the following before you execute the above sentence
if ULONG_MAX – r/10 >= x
No Overflow
else
overflow
NOTE:ULONG_MAX is normally defined in limits.h. And it is dependent on the Processor.
Share: