2

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

Community
  • 1
  • 1
Yousf
  • 3,957
  • 3
  • 27
  • 37
  • 1
    http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.15 – Flexo Sep 25 '11 at 16:50
  • I found that is it exact duplicate of http://stackoverflow.com/questions/24901/is-there-a-performance-difference-between-i-and-i-in-c – Yousf Sep 25 '11 at 16:59
  • 1
    While in this case not neccessary and funtionally indentical, it is just good practice, because as soon as `i` is of class type (e.g. an iterator), `++i` is usually more efficient. – Christian Rau Sep 25 '11 at 17:00

2 Answers2

4

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
Baz1nga
  • 15,485
  • 3
  • 35
  • 61
2

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.

Kaivosukeltaja
  • 15,541
  • 4
  • 40
  • 70
  • They're *not* identical, especially if `i` is not an integer type. – Flexo Sep 25 '11 at 16:53
  • 2
    @awoodland: The operators themselves aren't, but if used as the counting expression of a for loop like described in the question they are functionally identical. – Kaivosukeltaja Sep 25 '11 at 16:56
  • In the OPs case, they are functionally identical. – David Titarenco Sep 25 '11 at 16:57
  • `i++` and `++i` are not identical but in this case as a third statement of a for-loop the behaviour of that loop is exactly the same if the ++Operator is not modifyed. The answer of Kaivosukeltaja is in this case correct: it is a matter of preference – thomas Sep 25 '11 at 17:00