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

jake mckenzie :

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?

Eran :

First of all, since the while (i == i + 1) {} loop doesn't change the value of i, making this loop infinite is equivalent to choosing a value of i that satisfies i == i + 1.

There are many such values:

Let's start with the "exotic" ones:

double i = Double.POSITIVE_INFINITY;

or

double i =  Double.NEGATIVE_INFINITY;

The reason for these values satisfying i == i + 1 is stated in
JLS 15.18.2. Additive Operators (+ and -) for Numeric Types:

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

This is not surprising, since adding a finite value to an infinite value should result in an infinite value.

That said, most of the values of i that satisfy i == i + 1 are simply large double (or float) values:

For example:

double i = Double.MAX_VALUE;

or

double i = 1000000000000000000.0;

or

float i = 1000000000000000000.0f;

The double and float types have limited precision, so if you take a large enough double or float value, adding 1 to it will result in the same value.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=34846&siteId=1