for循环中的++i和i++有区别吗?这仅仅是语法问题吗?
当前回答
要理解FOR循环的作用
上图显示FOR可以转换为WHILE,因为它们最终具有完全相同的汇编代码(至少在gcc中)。所以我们可以把FOR分解成几部分,来理解它的功能。
for (i = 0; i < 5; ++i) {
DoSomethingA();
DoSomethingB();
}
等于WHILE版本
i = 0; //first argument (a statement) of for
while (i < 5 /*second argument (a condition) of for*/) {
DoSomethingA();
DoSomethingB();
++i; //third argument (another statement) of for
}
It means that you can use FOR as a simple version of WHILE: The first argument of FOR (int i) is executed, outside, before the loop. The third argument of FOR (i++ or ++i) is executed, inside, in the last line of the loop. TL:DR: no matter whether i++ or ++i, we know that when they are standalone, they make no difference but +1 on themselves. In school, they usually teach the i++ way, but there are also lots of people prefer the ++i way due to several reasons. NOTE: In the past, i++ has very little impact on the performance, as it does not only plus one by itself, but also keeps the original value in the register. But for now, it makes no difference as the compiler makes the plus one part the same.
其他回答
正如@Jon B所说,在for循环中没有区别。
但在一段时间或做…While循环,如果你与++i或i++进行比较,你会发现一些不同
while(i++ < 10) { ... } //compare then increment
while(++i < 10) { ... } //increment then compare
既然你问了循环中的区别,我猜你的意思是
for(int i=0; i<10; i++)
...;
在这种情况下,你在大多数语言中没有什么不同:无论你写i++还是++i,循环的行为都是一样的。在c++中,你可以编写自己版本的++操作符,如果i是用户定义的类型(例如,你自己的类),你可以为它们定义不同的含义。
上面的原因并不重要,因为您没有使用i++的值。另一件事是你做的时候
for(int i=0, a = 0; i<10; a = i++)
...;
现在,有一个区别,因为正如其他人指出的那样,i++意味着增量,但求值到之前的值,但++i意味着增量,但求值到i(因此它将求值到新值)。在上面的例子中,a被赋给i之前的值,而i是递增的。
一个(++i)是前增量,一个(i++)是后增量。区别在于表达式立即返回什么值。
// Psuedocode
int i = 0;
print i++; // Prints 0
print i; // Prints 1
int j = 0;
print ++j; // Prints 1
print j; // Prints 1
编辑:哎呀,完全忽略了循环方面的事情。在for循环中,当它是'step'部分(for(…;…。)),但它也可以在其他情况下发挥作用。
在c#中,在for循环中使用没有区别。
for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
输出和
for (int i = 0; i < 10; ++i) { Console.WriteLine(i); }
正如其他人指出的那样,在一般情况下i++和++i有一个微妙但显著的区别:
int i = 0;
Console.WriteLine(i++); // Prints 0
int j = 0;
Console.WriteLine(++j); // Prints 1
i++读取I的值,然后增加它。
++i增加i的值,然后读取它。
我很奇怪为什么这么多人把for循环中的增量表达式写成i++。
在for循环中,当第三个组件是一个简单的增量语句时,例如
for (i=0; i<x; i++)
or
for (i=0; i<x; ++i)
结果执行没有区别。
推荐文章
- 如何在for循环中注释类型?
- 在支持循环和函数的语言中,是否存在“goto”的合法用例?
- 为什么不使用异常作为常规的控制流呢?
- 列表推导式和函数式函数比for循环更快吗?
- 什么是序列化?
- 我怎么能循环通过一个列表<T>和抓取每个项目?
- 每个递归都可以转换成迭代吗?
- 去下一次迭代在java For循环
- 什么是ORM,它是如何工作的,我应该如何使用它?
- 我能在服务器端应用程序(PHP、Ruby、Python等)上读取URL的哈希部分吗?
- 元素在“for(…in…)”循环中排序
- 多少个参数是太多?
- 是否有可能在没有迭代器变量的情况下实现Python for range循环?
- 对于不可变集合上的非突变“add”方法,最好的名称是什么?
- foo到底是什么意思?