简体   繁体   中英

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.

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

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.

Replace

 counter = counter++;

by: 1)

counter+=1;

or

2)

counter++;

Cheers!

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM