Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this cause an infinite loop

Consider this simple code:

 // E1 
  public void doTest(String pattern) {
    int counter = 0;

    while (counter < 3) {
        counter = counter++;
    }
    System.out.println("Done");
}

This causes an infinite loop.

However if the statement that increments the counter is written like this:

E2.  counter = ++counter;

or this

E3.    counter++;

It terminates normally. I understand that the incrementing occurs after the assignment in the version that fails which explains why E2 works, but I thought java assigned the results of an increment in the variable that is incremented as in E3. So I'm perplexed as to why E1 fails but E3 does not.

like image 833
Elliott Avatar asked Jun 20 '13 21:06

Elliott


People also ask

What causes an infinite loop in a while loop?

An infinite loop is a loop that keeps running 'forever' (e.g., Liberty & MacDonald, 2009; Wikipedia, 2019). These loops don't exit like regular C# loops do, but instead use up computer resources and freeze our application. Most infinite loops are caused by either a coding or logic mistake.

What causes an infinite loop in Python?

A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.

What causes infinite loops in C++?

A loop becomes infinite loop if a condition never becomes false.


1 Answers

counter = counter++;

The above code has no effect on counter. It is effectively same as:

int temp = counter;
counter++;
counter = temp;

So, the value of counter is not changing at all.

On the other hand, if you use:

counter = ++counter;

The counter is incremented first, and then is re-assigned to counter. Essentially, you can simply ignore the assignment part, and keep it simply this:

counter++; // Or ++counter
like image 75
Rohit Jain Avatar answered Nov 02 '22 06:11

Rohit Jain