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

后端 未结 27 2454
-上瘾入骨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:03

    This loop is the same as this while loop:

    int i = 0;
    while(i < 5)
    {
         // LOOP
         i++; // Or ++i
    }
    

    So yes, it has to be the same.

    0 讨论(0)
  • 2020-11-30 07:04

    Because that statement is just on it's own. The order of the increment doesn't matter there.

    0 讨论(0)
  • 2020-11-30 07:04

    Because the value of y is calculated in for statement and the value of x is calculated in its own line, but in the System.out.println they are only referenced.

    If you decremented inside System.out.println, you would get different result.

    System.out.println(y--);
    System.out.println(--y);
    
    0 讨论(0)
  • 2020-11-30 07:05

    The increment is executed as an independent statement. So

    y--;

    and

    --y;

    are equivalent to each other, and both equivalent to

    y = y - 1;

    0 讨论(0)
  • 2020-11-30 07:06

    If the for loop used the result of the expression i++ or ++i for something, then it would be true, but that's not the case, it's there just because its side effect.

    That's why you can also put a void method there, not just a numeric expression.

    0 讨论(0)
  • 2020-11-30 07:07

    Yes it does it sequentially. Intialisation, then evaluation condition and if true then executing the body and then incrementing.

    Prefix and Postfix difference will be noticable only when you do an Assignment operation with the Increment/Decrement.

    0 讨论(0)
提交回复
热议问题