Lesson 44 +10 XP

Increment and Decrement

C++ Increment and Decrement

Counting is everywhere, so C++ has a shortcut: ++ adds 1, and -- subtracts 1.

The simple forms

int x = 5;
x++;     // x is now 6
x--;     // x is now 5
++x;     // same as x++, x is now 6
--x;     // x is back to 5

Used on their own line, prefix and postfix do exactly the same thing.

Prefix vs postfix

But if you use the result, the order matters:

  • Postfix x++: return the old value first, then add 1.
  • Prefix ++x: add 1 first, then return the new value.
int a = 5;
int b = a++;   // b is 5, a becomes 6
int c = ++a;   // a becomes 7, c is 7

Watch out for side effects

Inside a bigger expression, increments change the world while the expression runs, which is a classic source of puzzles. Readable code keeps ++ and -- on their own line.

int i = 0;
cout << i++;  // prints 0, then i becomes 1
cout << ++i;  // i becomes 2, then prints 2

TL;DR

  • ++ adds 1, -- subtracts 1.
  • Postfix x++ returns the old value, then increments.
  • Prefix ++x increments first.
  • Keep them on their own line for clean, predictable code.