The short answer
For a plain int in a simple loop, ++i and i++ usually behave the same, and compilers can often optimize away any difference. The preference for ++i mostly comes from class types, such as iterators. There, i++ may need to copy the object before it changes it.
What the postfix form has to do
The postfix form must give back the old value. For a built-in int, that is simple. For a class, the function has to save a copy of the old object, change the real object, and return the copy. The prefix form changes the object and returns a reference to it, so it does not need that copy.
class Counter {
public:
Counter& operator++() { // prefix: change the object, then return it
++value_;
return *this;
}
Counter operator++(int) { // postfix: save the old object first
Counter old = *this; // this copy is the extra cost
++value_;
return old;
}
private:
int value_ = 0;
};
This works through operator overloading in c, in which a class defines its own ++. The int in the postfix version is only a marker that tells C++ which version to use.
For a small int member, the copy is cheap. If the object holds a large string or a vector, the copy can be expensive.
Iterators in loops
Standard library iterators are a common place to use ++:
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {1, 2, 3};
for (auto it = nums.begin(); it != nums.end(); ++it) {
std::cout << *it << "\n";
}
return 0;
}
Many iterators are class types, so ++it can avoid the copy that it++ would need. Raw pointers are built-in types, and for them the difference is usually negligible.
When i++ is the right choice
Use the postfix form when you need the old value. For example:
#include <iostream>
int main() {
int values[3] = {10, 20, 30};
int i = 0;
int first = values[i++]; // uses index 0, then moves to index 1
std::cout << first << "\n";
return 0;
}
Assigning the current number to a new record and then moving the counter forward, as in int id = next_id++;, follows the same pattern.
For plain ints where the old value is not needed, either form works. Some teams prefer ++i everywhere for consistency.
Lvalues
There is one more difference. For a built-in type, ++i gives back the variable itself, so the result is an lvalue. i++ gives back a temporary value. If the term lvalue is new to you, the article What Does lvalue Mean? is a good next read.
Quick summary
- For plain
ints, the two forms usually perform the same. - For class types, the postfix form may copy the old object, so
++iis often preferred. - Use
i++when you need the value from before the change. - Pick one style and keep it consistent in your code.