For what value of i does while(i==i+1) {} loop forever?

  • A+
Category:Languages

I ran cross this puzzler from an advanced programming course at a UK university exam.

Consider the following loop, in which i is, so far, undeclared:

while(i == i + 1) {} 

Find the definition of i, that precedes this loop, such that the while loop continues for ever.

The next question, which asked the same question for this code snippet:

while(i != i) {} 

was obvious to me. Of course in this other situation it is NaN but I am really stuck on the prior one. Does this have to do with overflow? What would cause such a loop to loop for ever in java?

 


There are several options:

double i = Double.POSITIVE_INFINITY; 

or

double i =  Double.NEGATIVE_INFINITY; 

or

double i = Double.MAX_VALUE; 

There are actually many double values that produce this behavior. I didn't even have to use special values such as POSITIVE_INFINITY. The double type has limited precision, so if you take a large enough double value (such as (1000000000000000000.0), adding 1 to it will result in the same number. That's the same reason Double.MAX_VALUE produces this behavior.

For POSITIVE_INFINITY and NEGATIVE_INFINITY, it's just the behavior of these constants, which happens to make sense - adding a finite value to an infinite value should result in an infinite value.

This is defined in 15.18.2. Additive Operators (+ and -) for Numeric Types:

The sum of an infinity and a finite value is equal to the infinite operand.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: