Changing Variables

You often calculate the new value of a variable from its current one. A player picks up a coin, and their score goes up by 10:

int score = 30;
score = score + 10;
printf("%d\n", score);

This prints:

40

In math, score = score + 10 wouldn't make sense. But in C, = means “store”: first, the right side is calculated with the current value (30 + 10), and then the result, 40, is stored in score. The old value is overwritten.

Programs do this so often that C has shortcuts for it:

  • score += 10; means the same as score = score + 10;
  • score -= 10; means score = score - 10;
  • score *= 2; means score = score * 2;
  • score /= 2; means score = score / 2; (with an int, that's integer division)
  • score++; adds 1, and score--; subtracts 1
int money = 100;
money -= 30;  // you bought a book
money += 50;  // you sold an old game
money *= 2;   // grandma doubled your savings
printf("Money: %d EUR\n", money);

int visits = 0;
visits++;
visits++;
printf("Visits: %d\n", visits);

This prints:

Money: 240 EUR
Visits: 2

You'll see ++ a lot in loops, where it counts 1, 2, 3 and so on.

Typical mistakes, which the compiler on this site doesn't stop, so you only see a wrong result:

  • score + 10; on its own doesn't change the variable. The result is calculated and thrown away at once, because nothing stores it.
  • score =+ 10;, with the two signs swapped, means score = +10;: it stores 10 in the variable. Write +=: the plus before the equals sign, with no space between them.

Instructions

Below the first comment, add 10 to score with +=.

Below the second comment, take one life away from the player with --.

Below the third comment, double the score with *=. The program should then print:

Score: 100
Lives: 2

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

9/11