In a for loop with an int loop variable, there is almost certainly no practical difference: while in theory, ++i might be faster, in practice the compiler is almost certain to optimise the difference between them to nothing at all.
If writing generic code (i.e. code that uses a template type) that might use a user-defined type as a loop variable, ++i is preferred.
I always use i++ when i is an int (or short/ long/ iterator etc), mainly out of habit
No, in this case both snippets of code have the same output.
For people who are reading this post,
The summary which i understood was: ++i increments before i++ increments after
But, the catch is for(int i=0; i<3; ++i)
In the above statement, though i gets incremented before, the whole code of the loop is not executed. So it goes inside the for loop, executes rest of the code and then comes back again to check i value.
in the two snippets, there is no difference in wheni++ and i-- perform the increment (so it doesn’t make sense to say "++i increments before/ i++ increments after") - the only real difference between the statements is that i++ performs the increment and returns its old value, and ++i performs the increment and (essentially) returns the new value. Since we don’t use the returned value of either of i++ or ++i anywhere in either of the snippets, this return value is irrelevant, and so there is no observable difference of behaviour.
i does not get incremented first. The code inside the loop will be executed first and then increment takes place . So i++ and ++i works the same. You can check some flow charts of for loops to be more clear about them.
Flow of for loop goes from A -> (B -> D -> C) -> (B -> D -> C ) … so on
Hence “ANY” command which is part of block “C” will be executed only after completing part A,B and D.
Hence the increment will happen after executing part A,B,D.
Note that return value of part B will only matter for “for” loop. Rest will just be ignored.
Let C be consisting of two parts, C1 followed by C2.
Pre-increment
C1 = increment
C2 = return value
Post-increment
C1 = return value
C2 = increment
Here return value in both cases will differ but ultimately for loop is going to ignore return value as C is not part of B. And hence only increment part is actually important. It doesn’t make any difference if you interchange C1 and C2 in this case.
(But as @ssjgz said it might create a very small change in running (execution) time depending on compiler)
Let me know if anything is still unclear @me_so_cool