Why, given:
int a = ..., b = ... ;
is this unsafe:
a - b
but this is safe:
a > b
By safe I mean guaranteed not to be affected by overflows (I'm writing a Comparator
of ints).
Why, given:
int a = ..., b = ... ;
is this unsafe:
a - b
but this is safe:
a > b
By safe I mean guaranteed not to be affected by overflows (I'm writing a Comparator
of ints).
The comparison a > b
is itself safe, because neither a
nor b
are changed. The operation a - b
can be unsafe because overflow is possible.
However, a previous overflow may affect the correctness of such a comparison a > b
done later. Subtracting a really large negative number will result in overflow, in that the result can be less than the original number (in math, subtracting a negative number should increase the original number), meaning a > b
may be an unexpected result.
If a - b
is used in a Comparator
, at first it looks like it satisfies the contract of Comparator
: return a number less than zero, equal to zero, or greater than zero if the value is less than, equal to, or greater than another value. But that's only true if overflow does not occur.
If a = 1000
and b = Integer.MIN_VALUE + 100
(a very large negative number, -2147483548
), then a - b
will overflow. The true mathematical result would be 500 - Integer.MIN_VALUE
, a value larger than Integer.MAX_VALUE
(2147484548). So the positive return value would indicate that a > b
, which is obviously true.
But with overflow, the value winds up being less than zero (-2147482748
), erroneously indicating that a < b
.
Well it depends... See System.nanoTime(), which recommends t1 - t0 < 0, not t1 < t0
for time comparison...