Is there a difference in ++i
and i++
in a for
loop? Is it simply a syntax thing?
相关问题
- Why isn't mySet.erase(it++) undefined behavior
- Operator Precedence.. () and ++
- Operator Precedence.. () and ++
- Bash Post Increment
- Pre increment and post increment
相关文章
- C/C++ post-increment/-decrement and function call
- i++ vs. ++i in a JavaScript for loop
- Is the behavior of return x++; defined?
- What are the historical reasons C languages have p
- Difference between *ptr += 1 and *ptr++ in C
- Post Increment with respect to Sequence Points
- Why doesn't changing the pre to the post incre
- Post increment operator not incrementing in for lo
There can be a difference for loops. This is the practical application of post/pre-increment.
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).
Since you ask about the difference in a loop, i guess you mean
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 thei
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 doNow, there is a difference, because as others point out,
i++
means increment, but evaluate to the previous value, but++i
means increment, but evaluate toi
(thus it would evaluate to the new value). In the above case,a
is assigned the previous value of i, while i is incremented.There is more to ++i and i++ than loops and performance differences. ++i returns a l-value and i++ returns an r-value. Based on this, there are many things you can do to ( ++i ) but not to ( i++ ).