using ++counter instead of counter++ in for loops [duplicate]
Possible Duplicate:
Is there a performance difference between i++ and ++i in C++?
I saw many places where they use for loops like this:
for(i = 0; i < size; ++i){ do_stuff(); }
instead of (which I -& most of people- use)
for(i = 0; i < size; i++){ do开发者_JS百科_stuff(); }
++i
should exactly give the same result as i++
(unless operators overloaded differential). I saw it for normal for-loops and STL iterated for loops.
Why do they use ++i
instead of i++
? does any coding rules recommends this?
EDIT: closed cause I found that it is exact duplicate of Is there a performance difference between i++ and ++i in C++?
simply put: ++x is pre-increment and x++ is post-increment that is in the first x is incremented before being used and in the second x is incremented after being used.
example code:
int main()
{
int x = 5;
printf("x=%d\n", ++x);
printf("x=%d\n", x++);
printf("x=%d\n", x);
}
o/p:
x=6
x=6
x=7
The two are indeed identical, as the third part is executed after each iteration of the loop and it's return value is not used for anything. It's just a matter of preference.
精彩评论