0

Consider the following code :

public class Game {

    public static void main(String[] args) {

        int x = 0;
        while (x < 1) {
          x = x++;
        }

    }

}

With my compiler this code goes into infinite loop , but why ?

First , we place the value of x into x , and only then we add 1 to x , and afterwards I would expect that 1 < 1 would be false , and the while loop would terminate ...

But no , that doesn't happen .

So what might be the reason for the infinite loop ?

JAN
  • 21,236
  • 66
  • 181
  • 318
  • 2
    Sounds like an excellent question for a debugger. Step through it. Or put some log statements in there. – nhgrif Jan 22 '14 at 23:53
  • `x=x++;` leaves `x` unchanged - you increment it, and THEN replace it with the OLD value (the value before you incremented). – Dawood ibn Kareem Jan 22 '14 at 23:57
  • -1 for not checking out "Related" (second question there contains the answer) – sashkello Jan 22 '14 at 23:58
  • In particular, you seem to be confused when you say, "First, we place the value of x into x, and only then we add 1 to x". It is true that lexically the assignment is before the increment, but the value on the right-hand side of the assignment must be calculated before the assignment can occur. (And that value is the *old* value of x, since the increment is a *post*-increment). – David Conrad Jan 23 '14 at 00:24

4 Answers4

7

The expression x++ is a post-increment, meaning that it the value of the expression is the old value, 0, which is then assigned back to x, so x is always 0 after x = x++;.

To break out of the infinite loop, don't assign it back to x, leaving the post-increment value of x, 1, intact:

while (x < 1) {
   x++;
}
rgettman
  • 176,041
  • 30
  • 275
  • 357
1

x++ is pretty much equivalent to

some-temporary = x;
x = x + 1;
now use the value of some-temporary

So x = x++; is equivalent to

some-temporary = x;
x = x + 1;
x = some-temporary;

so you should be able to see why the part that adds 1 has no effect.

ajb
  • 31,309
  • 3
  • 58
  • 84
1

That is beacause x gets incremented after being used. So the expanded sequence of operations taking place would be:

  1. oldX = x
  2. x++, that is, x = x + 1
  3. x = oldX

oldX being a fictitious variable.

What happens is that x is always assigned oldX, which in our case is 0, resulting in an infinite loop. The x++ part is just ignored.

Solution: replace x = x++ with x++ or, if you really want, x = ++x.

Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
0

x = x++ doesn't do what you want. Replace it with x++.

x++ is equivalent to x = x + 1, so your assignment doesn't make sense.

More information about this can be found in answers here:

Why does this go into an infinite loop?

Community
  • 1
  • 1
sashkello
  • 17,306
  • 24
  • 81
  • 109