May 24 2007

How to Avoid Integer overflow in C?

Published by at 10:18 pm under C Programming

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 sentense

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.

Comments Off on How to Avoid Integer overflow in C?

Comments are closed at this time.