Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
public bool overflow(int a, int b)
{
    java.math.BigInteger ba = new java.math.BigInteger(String.valueOf(a));
    java.math.BigInteger bb = new java.math.BigInteger(String.valueOf(b));
    java.math.BigInteger br = ba.add(bb);
    if(br.compareTo(java.math.BigInteger.valueOf(Integer.MAX_VALUE)) == 1
              || br.compareTo(java.math.BigInteger.valueOf(Integer.MIN_VALUE))== -1)
        return true;//We have overflow
    //Can proceed
   return false
}

public int do_operation(int a, int b) throws ArithmeticException
{
      if (overflow(a,b))
         throw ArithmeticException;
      else //we are within range safely perform the addition
}

...

Code Block
bgColor#ccccff
int a,b,result;

long temp = (long)a-(long)b;
if(long < Integer.MIN_VALUE || long > Integer.MAX_VALUE)
throw ArithmeticException;
else
result = (int) temp;


Code Block
bgColor#ccccff

public bool underflow(int a, int b)
{
    java.math.BigInteger ba = new java.math.BigInteger(String.valueOf(a));
    java.math.BigInteger bb = new java.math.BigInteger(String.valueOf(b));
    java.math.BigInteger br = ba.subtract(bb);
    if(br.compareTo(java.math.BigInteger.valueOf(Integer.MAX_VALUE)) == 1
              || br.compareTo(java.math.BigInteger.valueOf(Integer.MIN_VALUE))== -1)
        return true;//We have underflow
    //Can proceed
   return false
}

public int do_operation(int a, int b) throws ArithmeticException
{
      if(undeflow(a,b))
         throw ArithmeticException;
      else //we are within range safely perform the addition
}





Multiplication


This noncompliant code example, can result in a signed integer overflow during the multiplication of the signed operands a and b. If this behaviour is unanticipated, the resulting value may lead to undefined behaviour

...