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

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

    They DON'T behave the same. The construct with i++ is slightly slower than the one with ++i because the former involves returning both the old and the new values of i. On the other side, the latter only returns the old value of i.

    Then, probably the compiler does a little magic and changes any isolated i++ into a ++i for performance reasons, but in terms of raw algorithm they are not strictly the same.

    0 讨论(0)
  • To visualize these things, expand the for loop to a while loop:

    for (int i = 0; i < 5; ++i) {
        do_stuff(i);
    }
    

    Expands to:

    int i = 0;
    while (i < 5) {
        do_stuff(i);
        ++i;
    }
    

    Whether you do post-increment or pre-increment on the loop counter doesn't matter, because the result of the increment expression (either the value before or after the increment) isn't used within the same statement.

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

    Those two cases are equivalent because the value of i is compared after the increment statement is done. However, if you did

    if (i++ < 3) 
    

    versus

    if (++i < 3)
    

    you'd have to worry about the order of things.

    And if you did

    i = ++i + i++;
    

    then you're just nuts.

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