Consider
#include <iostream>
int main() {
int x {9};
int y {22};
++x;
y++;
int myArray[3] = {1, 2, 3};
for(int i = 0; i < 3; ++i) {
std::cout << myArray[i] << " ";
}
}
Seems fairly harmless. Despite achieving the same result (incrementing the operand), the prefix and postfix versions have slight differences.
In terms of the loop variable i, does it matter if we do i++ vs ++i?
Prefix increment
Prefix increment increments the variable first, then evaluates to the updated value.
#include<iostream>
int main()
{
int oranges { 12 };
std::cout<< ++oranges << '\\n';
std::cout << oranges << '\\n';
}
// Output
13
13
Standard stuff. This is what we expect to see. Notice how the operand is permanently modified.
Postfix increment
Consider the following
#include <iostream>
int main()
{
int apples { 10 };
std::cout << "Sold: " << apples++ << '\\n';
std::cout << "Remaining: " << apples << '\\n';
}
// Output
Sold: 10
Remaining: 11
?? What happened? The value printed is the old value of apples, even though it’s been incremented.
Well, the postfix version does 3 things:
- Creates a copy of the operand
- Increments it
- Returns the copy
NOTE:: Despite the examples using the increment prefix/postfix operators, the same applies to the prefix/postfix decrement operators
When to use which?
Since postfix increment copies the operand, use it when you specifically need the operand to remain unmodified.
Use prefix increment when you only want to increment the operand. E.g. as a loop variable.
However, prefer the prefix versions, as they are more performant and less likely to cause side effects.