Codiqo

Learn C++ · lesson 12 of 61 · about 7 minutes

Updating Values

Pick up the loot: change values with += and ++, and choose between two values with condition ? a : b.

What you'll learn

  • Use ++, --, +=, -=, *=
  • Know the difference between x++ and ++x
  • Use condition ? a : b

Shortcuts

Games change values all the time. gold = gold + 10 works, and gold += 10 is the short way. -=, *= and /= work the same way, and ++ and -- add or take away 1.

x++ and ++x both add 1, but inside a bigger expression x++ gives the old value and ++x the new one. On a line of their own, they do the same thing.

Updating the hero

#include <iostream>

int main() {
    int gold = 5;
    int health = 85;
    gold += 10;
    health -= 20;
    gold *= 2;
    health++;
    std::cout << gold << " " << health << "\n";
}

Output

30 66

Choosing a value

condition ? a : b gives a when the condition is true and b when it's false. It picks a number or a word without a whole if. Put it in brackets inside std::cout, and make both choices the same kind of value: two numbers, or two pieces of text.

Picking with ?:

#include <iostream>

int main() {
    int health = 30;
    std::cout << (health > 50 ? "You feel fine" : "You feel weak") << "\n";
    int found = health < 50 ? 10 : 2;
    std::cout << "Found " << found << " gold\n";
}

Output

You feel weak
Found 10 gold

Tip

A const can't be updated: MAX_HEALTH += 5 doesn't compile, which is exactly what const is for.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.