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

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

    In C# there is no difference when used in a for loop.

    for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
    

    outputs the same thing as

    for (int i = 0; i < 10; ++i) { Console.WriteLine(i); }
    

    As others have pointed out, when used in general i++ and ++i have a subtle yet significant difference:

    int i = 0;
    Console.WriteLine(i++);   // Prints 0
    int j = 0;
    Console.WriteLine(++j);   // Prints 1
    

    i++ reads the value of i then increments it.

    ++i increments the value of i then reads it.

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

    i++ ; ++i ; both are similar as they are not used in an expression.

    class A {
    
         public static void main (String []args) {
    
         int j = 0 ;
         int k = 0 ;
         ++j;
         k++;
        System.out.println(k+" "+j);
    
    }}
    
    prints out :  1 1
    
    0 讨论(0)
  • 2020-11-22 00:39

    For i's of user-defined types, these operators could (but should not) have meaningfully different sematics in the context of a loop index, and this could (but should not) affect the behavior of the loop described.

    Also, in c++ it is generally safest to use the pre-increment form (++i) because it is more easily optimized. (Scott Langham beat me to this tidbit. Curse you, Scott)

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

    The question is:

    Is there a difference in ++i and i++ in a for loop?

    The answer is: No.

    Why does each and every other answer have to go into detailed explanations about pre and post incrementing when this is not even asked?

    This for-loop:

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

    Would translate to this code without using loops:

    int i = 0; // Initialization
    
    loopStart:
    if (i < 5) // Condition
    {
       Output(i);
    
       i++ or ++i; // Increment
    
       goto loopStart;
    }
    

    Now does it matter if you put i++ or ++i as increment here? No it does not as the return value of the increment operation is insignificant. i will be incremented AFTER the code's execution that is inside the for loop body.

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