17

Possible Duplicate:
Why use ++i instead of i++ in cases where the value is not used anywhere else in the statement?

OK, I must be loosing my Google-foo.

Someone at work noted during code review that one should always prefer ++variable as opposed to variable++ in C++ (when semantically there's no distinction). But the person didn't know the reason when I asked "why". Surprisingly, my Googling so far didn't yield an answer either, nor does SO's "related question".

So, the question stands: why would ++variable be preferred as opposed to variable++ in C++?

14

++i can mutate this, and then return *this. Contrarily, i++ has to return the old value. This means making a copy. For some iterators, for example, this can be quit a hit.

Consider:

expensive_iterator& operator++(void)
{
    /* do some increment */

    return *this;
}


expensive_iterator operator++(int)
{
    expensive_iterator old(*this); // expensive copy!

    /* do some increment */

    return old; // another potential copy! D:
}

It's that copy you want to avoid, and the easiest way to do that is to not call post-fix in the first place.

13 accepted

++i is potentially faster

UPDATED Here's one reference (C++ FAQ Lite):

http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.15

3

the pre and post increment/decrement operators change the value, and also return a value. For the pre increment case, there returned value is the final value. But for the post increment case, the final value is the value before increment.

If you don't do anything with the returned value, then a good optimizer will just throw it away, but when you do use it, or the optimizer isn't very good, what you are telling the code to do is this

 1. save the value of X into temp
 2. increment X
 3. return temp

This uses up a register and takes multiple instructions, while ++X is

 1. increment X
 2. return X
2

For native types, there is no difference in performance; a smart optimizing compiler will output identical assembly. In general, however, preincrement is preferable for two reasons:

  • Semantically it's usually what you mean. Preincrement means "increment this"; postincrement means "increment this and then give me its original value".

  • Because postincrement requires the original value to be returned, a copy containing that value is made. In cases where incrementing has other side effects, the compiler won't be able to optimize this away, so postincrement is more expensive.

1

With standard fundamental types, it makes no difference. The difference really comes into play with operator overloading and the possibility of it making copies of an object.