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

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

    Since you ask about the difference in a loop, i guess you mean

    for(int i=0; i<10; i++) 
        ...;
    

    In that case, you have no difference in most languages: The loop behaves the same regardless of whether you write i++ and ++i. In C++, you can write your own versions of the ++ operators, and you can define separate meanings for them, if the i is of a user defined type (your own class, for example).

    The reason why it doesn't matter above is because you don't use the value of i++. Another thing is when you do

    for(int i=0, a = 0; i<10; a = i++) 
        ...;
    

    Now, there is a difference, because as others point out, i++ means increment, but evaluate to the previous value, but ++i means increment, but evaluate to i (thus it would evaluate to the new value). In the above case, a is assigned the previous value of i, while i is incremented.

提交回复
热议问题