Why doesn't changing the pre to the post increment at the iteration part of a for loop make a difference?

后端 未结 27 2464
-上瘾入骨i
-上瘾入骨i 2020-11-30 06:22

Why does this

 int x = 2;
    for (int y =2; y>0;y--){
        System.out.println(x + \" \"+ y + \" \");
        x++;
    }

prints the s

27条回答
  •  一整个雨季
    2020-11-30 07:12

    There are a lot of good answers here, but in case this helps:

    Think of y-- and --y as expressions with side effects, or a statement followed by an expression. y-- is like this (think of these examples as pseudo-assembly):

    decrement y
    return y
    

    and --y does this:

    store y into t
    decrement y
    load t
    return t
    

    In your loop example, you are throwing away the returned value either way, and relying on the side effect only (the loop check happens AFTER the decrement statement is executed; it does not receive/check the value returned by the decrement).

提交回复
热议问题