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)   

结果执行没有区别。