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

后端 未结 22 1764
暗喜
暗喜 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:13

    There can be a difference for loops. This is the practical application of post/pre-increment.

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

    While the first one counts to 11 and loops 11 times, the second does not.

    Mostly this is rather used in a simple while(x-- > 0 ) ; - - Loop to iterate for example all elements of an array (exempting foreach-constructs here).

    0 讨论(0)
  • 2020-11-22 00:13

    They both increment the number. ++i is equivalent to i = i + 1.

    i++ and ++i are very similar but not exactly the same. Both increment the number, but ++i increments the number before the current expression is evaluated, whereas i++ increments the number after the expression is evaluated.

    int i = 3;
    int a = i++; // a = 3, i = 4
    int b = ++a; // b = 4, a = 
    

    Check this link.

    0 讨论(0)
  • 2020-11-22 00:14

    There is no actual difference in both cases 'i' will be incremented by 1.

    But there is a difference when you use it in an expression, for example:

    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
    
    0 讨论(0)
  • 2020-11-22 00:15

    Yes, there is a difference between ++i and i++ in a for loop, though in unusual use cases; when a loop variable with increment/decrement operator is used in the for block or within the loop test expression, or with one of the loop variables. No it is not simply a syntax thing.

    As i in a code means evaluate the expression i and the operator does not mean an evaluation but just an operation;

    • ++i means increment value of i by 1 and later evaluate i,
    • i++ means evaluate i and later increment value of i by 1.

    So, what are obtained from each two expressions differ because what is evaluated differs in each. All same for --i and i--

    For example;

    let i = 0
    
    i++ // evaluates to value of i, means evaluates to 0, later increments i by 1, i is now 1
    0
    i
    1
    ++i // increments i by 1, i is now 2, later evaluates to value of i, means evaluates to 2
    2
    i
    2
    

    In unusual use cases, however next example sounds useful or not does not matter, it shows a difference

    for(i=0, j=i; i<10; j=++i){
        console.log(j, i)
    }
    
    for(i=0, j=i; i<10; j=i++){
        console.log(j, i)
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 00:20

    There is no difference if you are not using the value after increment in the loop.

    for (int i = 0; i < 4; ++i){
    cout<<i;       
    }
    for (int i = 0; i < 4; i++){
    cout<<i;       
    }
    

    Both the loops will print 0123.

    But the difference comes when you uses the value after increment/decrement in your loop as below:

    Pre Increment Loop:

    for (int i = 0,k=0; i < 4; k=++i){
    cout<<i<<" ";       
    cout<<k<<" "; 
    }
    

    Output: 0 0 1 1 2 2 3 3

    Post Increment Loop:

    for (int i = 0, k=0; i < 4; k=i++){
    cout<<i<<" ";       
    cout<<k<<" "; 
    }
    

    Output: 0 0 1 0 2 1 3 2

    I hope the difference is clear by comparing the output. Point to note here is the increment/decrement is always performed at the end of the for loop and hence the results can be explained.

    0 讨论(0)
提交回复
热议问题