3.2 — Shortcuts for changing numbers
Read one box at a time. No rush.
Compound assignment#
Changing a variable using its own value is so common that C++ has shortcuts.
| Shortcut | Same as |
|---|---|
x += 5 | x = x + 5 |
x -= 5 | x = x - 5 |
x *= 5 | x = x * 5 |
x /= 5 | x = x / 5 |
x %= 5 | x = x % 5 |
C++
int score { 10 };score += 5; // 15score *= 2; // 30Add one, take one#
++ adds 1. -- takes away 1.
C++
int lives { 3 };++lives; // 4--lives; // 3++x vs x++#
++xadds 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.
Tip: press ← / → to move between lessons, / to search.