Reputation: 71
For the loop
int r = 10;
for(int h=0;h<r;h--)
{
r--;
}
out.print(r);
the output is -2147483639. I'm not sure why the loop wouldn't be infinitely repeating, and I can't quite figure out the significance of the outputted number (besides the fact that it is near the int MIN_VALUE). What exactly is happening?
Upvotes: 0
Views: 42
Reputation: 201429
In addition to overflow, there is arithmetic underflow. In your case, the value of h
underflows before r
(at which point, it is Integer.MAX_VALUE
) and thus h
is greater than r
and the loop ends.
int r = Integer.MIN_VALUE;
System.out.println(r);
r--;
System.out.println(r);
Output is
-2147483648
2147483647
Upvotes: 1
Reputation: 159086
r,h
starts out 10,0
, then each iteration counts down both by 1, e.g. 9,-1
, 8,-2
, and on.
Eventually, h
reaches Integer.MIN_VALUE
, i.e. r=-2147483638, h=-2147483648
, before it underflows the int
and becomes r=-2147483639, h=2147483647
, at which point h<r
becomes false
, and the loop ends.
Result: -2147483639
Note: If you change int
to long
, the underflow will still happen, it'll just take a heck of a lot longer.
Upvotes: 1