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

后端 未结 27 2472
-上瘾入骨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 06:51

    Because this:

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

    Effectively gets translated by the compiler to this:

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

    As you see, using y-- or --y doesn't result in any difference. It would make a difference if you wrote your loop like this, though:

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

    This would yield the same result as your two variants of the loop, but changing from --y to y-- here would break your program.

提交回复
热议问题