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_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++?

最佳答案

简而言之:++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.
示例代码:

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

10-01 06:18
查看更多