为什么在for循环的迭代部分不改变pre到post的增量会有所不同?

and*_*and 38 java post-increment

为什么这样呢

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

打印与此相同?

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

到目前为止,正如我所理解的那样,首先使用"按原样"增加后增量.是否先添加预增量然后再使用.为什么这不适用于for循环的主体?

Pau*_*and 58

循环相当于:

int x = 2;
{
   int y = 2;
   while (y > 0)
   {
      System.out.println(x + " "+ y + " ");
      x++;
      y--; // or --y;
   }
}
Run Code Online (Sandbox Code Playgroud)

从阅读该代码可以看出,在for循环的第三部分中使用post或pre decrement运算符无关紧要.

更一般地说,任何for循环的形式:

for (ForInit ; Expression ; ForUpdate)
    forLoopBody();
Run Code Online (Sandbox Code Playgroud)

完全等同于while循环:

{
    ForInit;
    while (Expression) {
        forLoopBody();
        ForUpdate;
    }
}
Run Code Online (Sandbox Code Playgroud)

for循环更紧凑,因此更容易解析这种常见的习语.


tda*_*ers 29

To visualize these things, expand the for loop to a while loop:

for (int i = 0; i < 5; ++i) {
    do_stuff(i);
}
Run Code Online (Sandbox Code Playgroud)

Expands to:

int i = 0;
while (i < 5) {
    do_stuff(i);
    ++i;
}
Run Code Online (Sandbox Code Playgroud)

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.


Bal*_*usC 17

如果这是您的关注,那么在性能方面没有区别.增量期间使用,它只能被错误地使用(因此对错误敏感).

考虑:

for (int i = 0; i < 3;)
   System.out.print(++i + ".."); //prints 1..2..3


for (int i = 0; i < 3;)
   System.out.print(i++ + ".."); //prints 0..1..2
Run Code Online (Sandbox Code Playgroud)

要么

for (int i = 0; i++ < 3;)
   System.out.print(i + ".."); //prints 1..2..3


for (int i = 0; ++i < 3;)
   System.out.print(i + ".."); //prints 1..2
Run Code Online (Sandbox Code Playgroud)

然而,有趣的细节是,正常的习惯用法是i++for语句的增量表达式中使用,并且Java编译器将编译它,就像++i使用它一样.


Sac*_*hag 13

++i and i++ makes a difference when used in combination with the assignment operator such as int num = i++ and int num = ++i or other expressions. In above FOR loop, there is only incrementing condition since it is not used in combination with any other expression, it does not make any difference. In this case it will only mean i = i + 1.

  • 13赞成?但这是错的!与赋值运算符一起使用时不是_only_:始终使用表达式的结果(例如,算术比较和方法参数). (6认同)
  • `for(int i = 0; i <10; doSomething(i ++))`或`for(i = -1; ++ i <10;)`如果用于前置或后置增量,真的会有所不同......所以是的,你的断言,即使它完全在`for`循环的上下文中(并再次读取它以检查你没有在第一句中指定上下文)是错误的. (2认同)

Ced*_* H. 6

此循环与此while循环相同:

int i = 0;
while(i < 5)
{
     // LOOP
     i++; // Or ++i
}
Run Code Online (Sandbox Code Playgroud)

所以是的,它必须是一样的.

  • @rmx:但不是'while(++ i <5)`而这就是重点 (2认同)

Noo*_*ilk 5

因为这个陈述就是它自己的.增量的顺序在那里并不重要.