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?
Pre-increment and Post-increment concept in C/C++? Decrement operator decrease the value by one. Pre-increment (++i) − Before assigning the value to the variable, the value is incremented by one. Post-increment (i++) − After assigning the value to the variable, the value is incremented.
Pre decrement means the value of the operator is decremented first and then assigned in the expression. Whereas the post decrement operator means the operand is first used in the expression and then performs the decrement operation to the operand's original value by 1.
Pre-Increment Operator in C Therefore, we can say that the pre-increment operator increases the value of the variable first and then use it in the expression. Syntax: b = ++a; For example, if the initial value of a were 5, then the value 6 would be assigned to b.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With