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.

其他回答

对于用户定义类型的i,这些操作符可以(但不应该)在循环索引上下文中具有有意义的不同语义,这可能(但不应该)影响所描述的循环的行为。

此外,在c++中,使用预增量形式(++i)通常是最安全的,因为它更容易优化。(斯科特·朗廷(Scott Langham)先我一步找到了这个花边新闻。诅咒你,斯科特)

在某些情况下,++i和i+1可能会给出不同的结果,-i, i - 1等也是如此。

这并不是因为递增和递减操作符的工作方式有缺陷,而是因为新程序员有时会忽略一个小事实。

根据经验,不要在数组的方括号内使用inc/dec。例如,我不会用arr[++ I]来代替arr[I + 1]。虽然两者得到的i值是一样的,但这里我们忽略了一些东西。

如果循环条件基于i的执行值,那么将arr[i + 1]替换为arr[++i]将导致错误。为什么?

假设i = 5,那么arr[i + 1]意味着arr[6],而arr[++i]虽然意味着arr[6],但也会将i的值改变为6,这可能不是我们想要做的事情。我们可能不想改变i的值,但由于一个简单的++/——操作符,我们改变了这个值。

所以在使用++/——操作符时要小心。

我希望我能使我的观点更容易理解。

在这两种情况下,'i'将加1。

但是当你在表达式中使用它时,就有区别了,例如:

int i = 1;
int a = ++i;
// i is incremented by one and then assigned to a.
// Both i and a are now 2.
int b = i++;
// i is assigned to b and then incremented by one.
// b is now 2, and i is now 3

正如@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是递增的。