Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

types

loops

People also ask

What is infinite loop example?

What is an Infinite Loop? An infinite loop occurs when a condition always evaluates to true. Usually, this is an error. For example, you might have a loop that decrements until it reaches 0. public void sillyLoop( int i ) { while ( i != 0 ) { i-- ; } }

What is the value of i after the for loop?

It gives always as zero.

How do you make an infinite while loop?

while loop represents the infinite condition as we provide the '1' value inside the loop condition. As we already know that non-zero integer represents the true condition, so this loop will run infinite times. We can also use the goto statement to define the infinite loop.

What is an infinite loop How infinite loop is declared?

An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so that it repeats indefinitely. In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.


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.


These puzzles are described in detail in the "Java Puzzlers: Traps, Pitfalls, and Corner Cases" book by Joshua Bloch and Neal Gafter.

double i = Double.POSITIVE_INFINITY;
while (i == i + 1) {}

or:

double i = 1.0e40;
while (i == i + 1) {}

both will result in an infinite loop, because adding 1 to a floating-point value that is sufficiently large will not change the value, because it doesn't "bridge the gap" to its successor1.

A note about the second puzzle (for future readers):

double i = Double.NaN;
while (i != i) {}

also results in an infinite loop, because NaN is not equal to any floating-point value, including itself 2.


1 - Java Puzzlers: Traps, Pitfalls, and Corner Cases (chapter 4 - Loopy Puzzlers).

2 - JLS §15.21.1


double i = Double.POSITIVE_INFINITY;