Difference between pre-increment and post-increment in a loop?

后端 未结 22 1820
暗喜
暗喜 2020-11-21 23:41

Is there a difference in ++i and i++ in a for loop? Is it simply a syntax thing?

22条回答
  •  一个人的身影
    2020-11-22 00:19

    Pre-increment ++i increments the value of i and evaluates to the new incremented value.

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

    Post-increment i++ increments the value of i and evaluates to the original non-incremented value.

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

    In C++, the pre-increment is usually preferred where you can use either.

    This is because if you use post-increment, it can require the compiler to have to generate code that creates an extra temporary variable. This is because both the previous and new values of the variable being incremented need to be held somewhere because they may be needed elsewhere in the expression being evaluated.

    So, in C++ at least, there can be a performance difference which guides your choice of which to use.

    This is mainly only a problem when the variable being incremented is a user defined type with an overridden ++ operator. For primitive types (int, etc) there's no performance difference. But, it's worth sticking to the pre-increment operator as a guideline unless the post-increment operator is definitely what's required.

    There's some more discussion here.

    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.


    In other languages such as C# where the ++ operator can't be overloaded there is no performance difference. Used in a loop to advance the loop variable, the pre and post increment operators are equivalent.

    Correction: overloading ++ in C# is allowed. It seems though, that compared to C++, in C# you cannot overload the pre and post versions independently. So, I would assume that if the result of calling ++ in C# is not assigned to a variable or used as part of a complex expression, then the compiler would reduce the pre and post versions of ++ down to code that performs equivalently.

提交回复
热议问题