Versions Compared

Key

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

...

Code Block
bgColor#FFcccc
public int do_operation(int a,int b)
{
   int temp = a - b;
//Could result in overflow
//perform other processing
   return temp;
}



Compliant Code Example

The appropriate way is to check explicitely the range before doing the subtraction

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;

A BigInteger class as a test-wrapper could be used

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
}

...

It is identical to the right-shift operator if the shifted value is positive. If it is negative the sign value can
change because the left-operand high-order bit is not retained and the sign value can change; Excerpt
from JLS:
"if n is negative, the result is equal to that of the expression (n>>s)(2<<~s) if the type of the left-hand operand is int, and to the result of the expression (n>>s)(2L<<~s) if the type of the left-hand operand is long. The added term (2<<~s) or (2L<<~s) cancels out the propagated sign bit. (Note that, because of the implicit masking of the right-hand operand of a shift operator, ~s as a shift distance is equivalent to 31-s when shifting an int value and to 63-s when shifting a longvalue.)"

...