for循环中的++i和i++有区别吗?这仅仅是语法问题吗?


当前回答

我很奇怪为什么这么多人把for循环中的增量表达式写成i++。

在for循环中,当第三个组件是一个简单的增量语句时,例如

for (i=0; i<x; i++)  

or

for (i=0; i<x; ++i)   

结果执行没有区别。

其他回答

问题是:

for循环中的++i和i++有区别吗?

答案是:不。

为什么每个答案都必须详细解释前增量和后增量,而这个问题甚至都没有问过?

这样的循环:

for (int i = 0; // Initialization
     i < 5;     // Condition
     i++)       // Increment
{
   Output(i);
}

在不使用循环的情况下转换为下面的代码:

int i = 0; // Initialization

loopStart:
if (i < 5) // Condition
{
   Output(i);

   i++ or ++i; // Increment

   goto loopStart;
}

现在你把i++还是++i作为增量有关系吗?不,它不会,因为增量操作的返回值是不重要的。i将在for循环体内的代码执行之后递增。

Pre-increment ++i增加i的值,并计算为新的增量值。

int i = 3;
int preIncrementResult = ++i;
Assert( preIncrementResult == 4 );
Assert( i == 4 );

后增量i++增加i的值,并计算为原始的非增量值。

int i = 3;
int postIncrementResult = i++;
Assert( postIncrementtResult == 3 );
Assert( i == 4 );

在c++中,如果可以使用前递增,则通常是首选。

这是因为如果使用后增量,它可能要求编译器必须生成创建额外临时变量的代码。这是因为被递增的变量的前值和新值都需要保存在某个地方,因为它们可能在被求值的表达式的其他地方被需要。

因此,至少在c++中,可以有性能差异来指导您选择使用哪一种。

这主要只在被递增的变量是用户定义的具有重写++操作符的类型时才会出现问题。对于基本类型(int等),没有性能差异。但是,作为指导原则,坚持使用前增量操作符是值得的,除非确实需要后增量操作符。

这里还有一些讨论。

In C++ if you're using STL, then you may be using for loops with iterators. These mainly have overridden ++ operators, so sticking to pre-increment is a good idea. Compilers get smarter all the time though, and newer ones may be able to perform optimizations that mean there's no performance difference - especially if the type being incremented is defined inline in header file (as STL implementations often are) so that the compiler can see how the method is implemented and can then know what optimizations are safe to perform. Even so, it's probably still worth sticking to pre-increment because loops get executed lots of times and this means a small performance penalty could soon get amplified.


在其他语言(如c#)中,c++操作符不能重载,在性能上没有区别。在循环中用于使循环变量前进,前增量操作符和后增量操作符是等效的。

更正:在c#中重载c++是允许的。不过,与c++相比,在c#中,你不能独立地重载前版本和后版本。因此,我假设在c#中调用++的结果没有被赋值给变量或用作复杂表达式的一部分,那么编译器会将++的前后版本简化为执行等效的代码。

正如@Jon B所说,在for循环中没有区别。

但在一段时间或做…While循环,如果你与++i或i++进行比较,你会发现一些不同

while(i++ < 10) { ... } //compare then increment

while(++i < 10) { ... } //increment then compare

对于循环可能会有不同。这是后增量/前增量的实际应用。

        int i = 0;
        while(i++ <= 10) {
            Console.Write(i);
        }
        Console.Write(System.Environment.NewLine);

        i = 0;
        while(++i <= 10) {
            Console.Write(i);
        }
        Console.ReadLine();

虽然第一个数到11,循环11次,但第二个不是。

这通常用于简单的while(x——> 0);- -循环迭代数组中的所有元素(这里不包括foreach-construct)。

我很奇怪为什么这么多人把for循环中的增量表达式写成i++。

在for循环中,当第三个组件是一个简单的增量语句时,例如

for (i=0; i<x; i++)  

or

for (i=0; i<x; ++i)   

结果执行没有区别。