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

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

提交回复
热议问题