September 17, 2008

Math.abs has an edge case...

Consider the following Java code:

  1.   int ai = Math.abs( i );
  2.   assert ai >= 0;

Will the assert ever fire?

Yes, it turns out that it can fire if i = Integer.MIN_VALUE, and you have been warned about this in the Math.abs javadoc, which states “Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.

Keep this in mind when looking at such innocent looking code...

Posted 13 years, 10 months ago on September 17, 2008
The trackback url for this post is https://www.eyt.ca/blog/bblog/trackback.php/138/

Comments have now been turned off for this post. If you want to share something, please e-mail me.


Recent Posts