开发者

using ++counter instead of counter++ in for loops [duplicate]

This question already has answers here: Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜