Pre vs. Post Increment & Decrement Operator in C++
If you've worked with C++, even at a basic level, you've likely encountered pre-increment (++x), pre-decrement (--x), post-increment (x++), and post-decrement (x--). While these operators may behave similarly in C, they have distinct differences in C++.
For reference

Pre-Increment Operator (++x)
Think of this operator as simply adding 1 to x. For example:
int main() {
int x = 0;
// Equivalent to y = x + 1;
int y = ++x;
// Prints `1`
std::cout << y << std::endl;
}
pre-increment operator c++ code block
Here, x is incremented first, and then the new value is assigned to y.
Post-Increment Operator (x++)
Unlike pre-increment, the post-increment operator returns the original value of x before incrementing it. As cppreference explains, this operator creates a temporary copy of the object, then increments the original.
int main() {
int x = 0;
int y = x++;
// Prints `0`
std::cout << y << std::endl;
// Prints `1`
std::cout << x << std::endl;
}
post-increment operator c++ code block
Why is the output 0 instead of 1? Let's break it down:
- A copy of
xis created (bothxand its copy are0). xis incremented to1.yis assigned the initial value ofx(which was0).- As a result,
xbecomes1, whileyremains0.
A similar approach works for the pre- and post- decrement operators.
When to Use Pre- vs. Post-Increment/Decrement
It depends on what you need from your code.
- If you need the variable to be incremented/decremented before assignment or evaluation, use pre-increment/decrement (
++x,--x). - If you need to retain the original value before modifying it, use post-increment/decrement (
x++,x--).
Operator Overloading
C++ allows operator overloading, so both pre- and post-increment/decrement can be customized for user-defined types. The Standard Library (STL) leverages this for types like std::atomic<T> and std::chrono::duration<Rep, Period>, enabling them to support these operators seamlessly.