Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Updating 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;
std::cout << score << "\n";

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;
  • 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
std::cout << "Money: " << money << " EUR\n";

int visits = 0;
visits++;
visits++;
std::cout << "Visits: " << visits << "\n";

This prints:

Money: 240 EUR
Visits: 2

You'll see ++ mostly in loops, where it counts 1, 2, 3 and so on. It's even in the name of the language: C++ is the C language, made one better.

Typical mistakes:

  • score + 10; on its own doesn't change the variable. The result is calculated and thrown away at once, because nothing stores it. The program still compiles, so you don't see an error, only a wrong result.
  • score =+ 10;, with the two signs swapped, compiles too, but it means score = +10;: it stores 10 in the variable. Write +=: the plus before the equals sign, with no space between them.

Instructions

  1. 1

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

  2. 2

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

  3. 3

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

    Score: 100
    Lives: 2
Back

8/11

  1. 1. Creating Variables
  2. 2. Printing Variables
  3. 3. Initialization and Assignment
  4. 4. Data Types
  5. 5. Arithmetic
  6. 6. Integer Division
  7. 7. Quiz: Integer Division
  8. 8. Updating Variables
  9. 9. Joining Text
  10. 10. Quiz: Joining Text
  11. 11. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.