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.
此循环与此while
循环相同:
int i = 0;
while(i < 5)
{
// LOOP
i++; // Or ++i
}
Run Code Online (Sandbox Code Playgroud)
所以是的,它必须是一样的.