Is i-​- special in while loop?

Davy Jones :

I was working on a while loop which has i-- decrease but I was expecting 10 to use twice. In my opinion, we use 10 at the beginning and then while loop starts. We write 10 because of System.out.println(i); and then we see i--; .. So I think we have 10 again to use and then we decrease it to the 9. Can you explain why the output returns as below?

int i=10;

 while(i>1){

  System.out.println(i);

  i--;

 }

Expected output is 10 10 9 8 7 6 5 4 3 2

but it gives 10 9 8 7 6 5 4 3 2

GhostCat salutes Monica C. :

Misconception on your end: these pre/post fix operations only affect the "current" expression. They have no notion of some enclosing loop context for example. You assume that the --i somehow magically affects the while condition. It doesn't. See here for some further reading.

Your code goes:

  1. i = 10
  2. is i > 10 ... sure: enter the loop
  3. print i
  4. i = i -1
  5. goto 2

In other words: if you want to see differences in the printed output, change your code to do:

System.out.println(--i);
System.out.println(i--);

for example.

In your code, you have that operation on its own line. Therefore, that line could be written as i--, --i, or i = i -1 or i -= 1. Doesn't matter. The expression decrements i, and stores the new value. Again: to see different outcome, you need to use the result of that operation directly!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116983&siteId=1