Why does this cause an infinite loop
Asked Answered
A

4

5

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.

Aceldama answered 20/6, 2013 at 21:4 Comment(3)
Do you know how to use a dubugger? This is a great tool which can help you understand how code like this works.Almanza
#3831841Compensation
possible duplicate of Is there a difference between x++ and ++x in java?Tangerine
C
17
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
Cyclades answered 20/6, 2013 at 21:5 Comment(1)
@Elliott, you can further understand this by reading up on post and pre increments here: en.wikipedia.org/wiki/Increment_and_decrement_operatorsOrganic
D
2

The problem is that the value of counter at the end of the loop body is the same as it was at the beginning. The statement counter = counter++ is equivalent to:

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

The postIncrement++ operator returns the value before the increment; the ++preIncrement operator returns the incremented value.

Degeneracy answered 20/6, 2013 at 21:6 Comment(0)
T
1

Replace

 counter = counter++;

by: 1)

counter+=1;

or

2)

counter++;

Cheers!

Trombidiasis answered 15/8, 2013 at 4:47 Comment(0)
C
0

It is better to avoid this kind assignment. The ++ is intended to be used by itself. If you want to increment by yourself you could have done counter += 1.

Compensation answered 15/8, 2013 at 4:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.