Pre vs. Post Increment & Decrement Operator in C++

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

Increment/decrement operators - cppreference.com

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:

  1. A copy of x is created (both x and its copy are 0).
  2. x is incremented to 1.
  3. y is assigned the initial value of x (which was 0).
  4. As a result, x becomes 1, while y remains 0.

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.