Possible Duplicates:
Why use ++i instead of i++ in cases where the value is not used anywhere else in the statement?
Incrementing in C++ - When to use x++ or ++x?
i++ vs. ++i
When is this used in real scenarios?
Possible Duplicates:
Why use ++i instead of i++ in cases where the value is not used anywhere else in the statement?
Incrementing in C++ - When to use x++ or ++x?
i++ vs. ++i
When is this used in real scenarios?
The obvious is when you want the old value returned, you use post-increment.
The more subtle things are that pre-increment should really never be slower and could be faster due to the lack of creating a temporary and returning the old value when using post-increment.
A real scenario for using post-increment in C++ is when erasing from standard containers. For example:
set<int> ctr;
ctr.insert(1);
ctr.insert(10);
ctr.insert(12);
ctr.insert(15);
set<int>::iterator it = set.begin();
// Post-increment so the value returned to erase is that of the previous
// iteration (i.e. begin()), yet the iterator stays valid due to the local
// iterator being incremented prior to the erase call
ctr.erase(it++);
// Still valid iterator can be used.
cout << "Value: " << *it << "\n";
In response to the compiler optimization, it is true yet I think it's always important to convey as precisely as possible what you're trying to accomplish. If you don't need the returned value from x++, then don't ask for it. Also, I'm not sure you would always get the same optimization if the type your incrementing is not a simple type. Think iterators that are not just plain pointers. In cases such as this, your mileage may vary with regard to optimization. In short, always pre-increment unless you need the returned (i.e. old value) of the post-increment operator.
The best explanation in order to clarify the differences is:
That is the crucial difference one increments AFTER the statement is evaluated, the other is incremented BEFORE the statement is evaluated.
I prefer to use i++
unless I specifically need the behavior of ++i
, because that puts the variable on the left, consistent with i += N
. Mostly this is minor, but in for-loops, I consider ++i
to be wrong and will change it to i++
en passant, because
for (i = 0; i < limit; ++i)
trips the reader up with lack of parallel structure;
for (i = 0; i < limit; i++)
is much nicer to read, because the loop variable is in the same position in all three clauses.
Arguments from performance are hogwash. Any compiler worth its salt will generate exactly the same code in cases where the difference doesn't matter. Yes, that includes cases involving C++ overloaded operators.