3.2 — Shortcuts for changing numbers

📘 Chapter 3⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Compound assignment#

Changing a variable using its own value is so common that C++ has shortcuts.

ShortcutSame as
x += 5x = x + 5
x -= 5x = x - 5
x *= 5x = x * 5
x /= 5x = x / 5
x %= 5x = x % 5
C++
int score { 10 };score += 5;   // 15score *= 2;   // 30

Add one, take one#

++ adds 1. -- takes away 1.

C++
int lives { 3 };++lives;   // 4--lives;   // 3

++x vs x++#

  • ++x adds one, then gives the new value.
  • x++ gives the old value, then adds one.
C++
int a { 5 };std::cout << ++a;   // prints 6 (a is now 6) int b { 5 };std::cout << b++;   // prints 5 (b is now 6)
Good habit

Use ++x by default. Only use x++ if you really need the old value. And never use ++ on the same variable twice in one line — the result can be undefined.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.