为什么会这样?
int x = 2;
for (int y =2; y>0;y--){
System.out.println(x + " "+ y + " ");
x++;
}打印的内容和这个一样吗?
int x = 2;
for (int y =2; y>0;--y){
System.out.println(x + " "+ y + " ");
x++;
}据我所知,post-increment是先“原样”使用,然后再递增。是前置增量,先加后用。为什么这不适用于for循环的主体?
发布于 2009-12-17 06:20:03
该循环等同于:
int x = 2;
{
int y = 2;
while (y > 0)
{
System.out.println(x + " "+ y + " ");
x++;
y--; // or --y;
}
}从阅读该代码可以看出,在for循环的第三部分中使用post或pre减量运算符并不重要。
更一般的是,任何形式的for循环:
for (ForInit ; Expression ; ForUpdate)
forLoopBody();完全等同于while循环:
{
ForInit;
while (Expression) {
forLoopBody();
ForUpdate;
}
}for循环更紧凑,因此更容易解析这种常见的习惯用法。
发布于 2010-08-18 18:19:58
要可视化这些内容,请将for循环展开为while循环:
for (int i = 0; i < 5; ++i) {
do_stuff(i);
}扩展为:
int i = 0;
while (i < 5) {
do_stuff(i);
++i;
}在循环计数器上执行后增量还是前增量并不重要,因为增量表达式的结果(增量之前或之后的值)不会在同一条语句中使用。
发布于 2010-04-13 00:45:53
如果这是您所关心的,那么在性能方面没有区别。只有在增量期间使用它时,它才能被错误地使用(因此对错误很敏感)。
考虑一下:
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或
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然而,有趣的细节是,通常的习惯用法是在for语句的增量表达式中使用i++,并且Java编译器将像使用++i一样对其进行编译。
https://stackoverflow.com/questions/1918196
复制相似问题