This article describes the similarities and differences between pre-increment and post-increment in C++ and the requirements that dictate which one you should use.
What’s the same
Whether we pre-increment (++x) or post-increment (x++), we are adding one to the value of the variable (x += 1).
int x = 5; ++x; std::cout << x << std::endl; // prints "6" x++; std::cout << x << std::endl; // prints "7"
The only difference between the two operations is the return type.
As the function signature for pre-increment (++x) reveals, it adds one to the supplied object and returns a reference to this modified object.
// Function signature for pre-increment operator in custom class. Example & operator++();
In contrast, the function signature for post-increment (x++) returns by value. It copies the value before modification, adds one to the supplied object, and returns the original copied value as an unnamed temporary object.
// Function signature for post-increment operator in custom class. // The dummy int argument only denotes post-increment. Example operator++(int);
Your intent decides which operation you should use
- If you don’t care about the return type because you aren’t capturing it, you should stick to the prefix form (++x) because it doesn’t waste time creating a temporary object that you won’t use.
- If you want to increment and immediately use the object you should use pre-increment (++x).
- If you want to increment an object but retrieve a copy of its value before it was modified you should use post-increment (x++).
Stick to pre-increment (++x) in almost all situations with the rare exception being when you want a copy of the variable before it was incremented.
int a = 5; int b = 5; int c = a++; // c == 5 int d = ++b; // d == 6 int & e = ++a; // e now references a which has been incremented to 7 int & f = b++; // compile time error - non const reference to temporary