简体   繁体   中英

Increment variable in loop, unexpected result

Code snippet:

int i=0;

for(int i=0;i<1;i++){
    i=--i-i--;
    System.out.println("for loop i= "+i);
}
System.out.println("i value outside for loop= "+i);

output:

for loop i= 0
i value outside for loop= 1

The value of i inside for loop is zero and outside for loop i is 1. Could you please help me understand it?

i=--ii--; changes the value of i to -1 and then back to 0 , because it assigns to it -1-(-1) , which is 0 . The reason for this result is that pre-decrement operator - --i - returns the decremented value -1 while post-decrement operator - i-- - returns the value prior to decrementing it (therefore it returns -1 instead of -2 ).

However, the loop's i++ clause increments i to 1, which causes the loop to terminate. Therefore the value of i is 1 after the loop.

Note that you have a typo in your question. You are declaring i twice in the same scope. In order for the code to pass compilation (and display the output you claim you got), you should change it to:

int i=0;

for (i = 0; i < 1; i++) {
    i = --i-i--;
    System.out.println("for loop i= "+i);
}
System.out.println("i value outside for loop= "+i);

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