We help IT Professionals succeed at work.

How to detect integer addition overflow?

rernst
rernst asked
on
Is there a simple and efficient way to detect range overflow when adding or multiplying two integer variables?
Comment
Watch Question

int m= 100000000;
int j = 20000;
int k = m*j;
if ( (k > Integer.MAX_VALUE) || (k < 0))
    System.out.println("Overflow");
System.out.println(Integer.MAX_VALUE);
System.out.println(k);

Java does not treat interger overflow as an error. It still computes the value and gives a negative number if the value is greater than 2147483646.

Author

Commented:
Hi rajesh_bala,

  unfortunately this is not the only case that could lead to overflow, so you'd have to check all possibilities. This would lead to considerable overhead. I thought of something more smart, isn't there something like checking a CARRY Or OVERFLOW bit?

Author

Commented:
Besides that,

int k;
(k > Integer.MAX_VALUE)

this expression should never be true!
Also, if you are multiplying 6 * -1 your test would evaluate true for overflow - when that clearly isn't the case.

Since overflow isn't treated as an error, you must either - pre-qualify your conditions to ensure overflow doesn't happen - or use a datatype that can handle the values you expect to use.  long and BigInteger seem appropriate.
To answer your question:  There is no simple way to detect overflow - you have to prevent it.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.