Search code examples
mathoverflowguavainteger-arithmeticunderflow

Condition for overflow in google guava library


This is the code for LongMath.checkedAdd() method which throws Arithmetic exception on overflow or underflow.

public static long checkedAdd(long a, long b) {
  long result = a + b;
  checkNoOverflow((a ^ b) < 0 | (a ^ result) >= 0);
  return result;
}

static void checkNoOverflow(boolean condition) {
  if (!condition) {
    throw new ArithmeticException("overflow");
  }
}

I understand why this API is testing for (a ^ result) but I don't understand the reason to include this condition : (a ^ b) < 0 . How does testing that the numbers are of opposite signs help?


Solution

  • As GregS wrote, If a and b are of opposite signs(*) then addition of them cannot possibly overflow. Now, if they're of the same sign, the sign of the result must be the same if there's mo overflow.


    (*) With zero and positive treated the same, which doesn't matter and makes the condition simple.