1

I expected post-increment and pre-increment of a variable and assignment of the result to itself to work a bit differently. But while the latter works as expected, the former runs as infinite while loop. Could someone please point out what i am missing here?

int y = 0;
int z = 4;

while(y<z)
{
    System.out.println(y);
    y =y++;//this prints 0 infinite times, shouldn't why be assigned values 0,1,2,3 with each pass?
    //y =++y;//this works as expected
}

Thank you

STaefi
  • 4,297
  • 1
  • 25
  • 43
Mangala G
  • 31
  • 5
  • Just use `y++`. – Robby Cornelissen Dec 25 '18 at 08:28
  • 2
    What I think is happening is this: 1) a temporary value of `y` is stored somewhere, 2) `y` is incremented by one, then 3) `y` is assigned back to the temporary value. Hence, the value of `y` never actually changes. Anyway who has an exact duplicate feel free to hammer. – Tim Biegeleisen Dec 25 '18 at 08:30

1 Answers1

1

As described in this StackOverflow answer, post increment works by storing a copy of y, adding 1 and returning the copy. This means that the return value of y++ is not y+1, but still only y. Since you are overwriting y with y++, you are essentially just saying y = y.

Sam Hollenbach
  • 652
  • 4
  • 19