Step 4 of 6
Shorthand operators
Changing a variable based on its own value is so common that C has shortcuts for it. These compound assignment operators do the math and store the result in one step:
| Shorthand | Means |
|---|---|
x += 5; |
x = x + 5; |
x -= 5; |
x = x - 5; |
x *= 2; |
x = x * 2; |
x /= 2; |
x = x / 2; |
x %= 3; |
x = x % 3; |
x++; |
x = x + 1; (increment) |
x--; |
x = x - 1; (decrement) |
#include <stdio.h>
int main(void) {
int gold = 10;
gold += 15;
printf("%d\n", gold);
gold /= 5;
printf("%d\n", gold);
gold--;
printf("%d\n", gold);
return 0;
}
25
5
4
The shorthand means exactly the same as the long form; it's just shorter and harder to mistype (you don't have to repeat a long variable name). ++ and -- are everywhere in C, especially for counting in loops, which is where the name C++ comes from: "C, plus one".
Common mistakes
x =+ 5;(the characters swapped) is valid C, but it meansx = +5;, which setsxto 5. The operator is+=.- There's no
**power operator. For powers you multiply, or use thepowfunction from<math.h>.
Your turn: fill in the shorthand operators so the program prints Streak: 12.