Is there a difference in ++i
and i++
in a for
loop? Is it simply a syntax thing?
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.