Variables, Types and Operators

Prefix vs postfix increment in C++

What's the difference between the prefix and postfix increment/decrement operators in C++? When should I use one over the other?

Abstract art representing computer programming

In C++, the increment (++) and decrement (--) operators come in two forms: prefix and postfix. They both increment or decrement the variable, but they differ in when this incrementing/decrementing takes effect.

  1. Prefix increment/decrement (++x-x): Increments/decrements the value of x, and then returns the new value of x.
  2. Postfix increment/decrement (x++x--): Returns the current value of x, and then increments/decrements x.

Here's an example that demonstrates the difference:

#include <iostream>

int main() {
  int x = 5;
  int y = ++x;  // y is 6, x is 6
  int z = x++;  // z is 6, x is 7

  // Outputs "7 6 6"
  std::cout << x << ' ' << y << ' ' << z;  
}
7 6 6

In the first case, x is incremented before its value is assigned to y, so both x and y end up as 6.

In the second case, the current value of x (which is 6) is assigned to z, and then x is incremented. So z ends up as 6 and x ends up as 7.

As for when to use one over the other, it largely depends on your specific needs. If you don't need the original value, the prefix version is usually preferred as it can be slightly more efficient. The postfix version is useful when you need to use the original value for something else in the same expression.

However, in most cases, it's best to increment/decrement in a separate statement to avoid confusion and potential bugs. The difference between prefix and postfix is most important when the increment/decrement is part of a larger expression.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved