C/C++ Arena

Step 3 of 6

Changing a variable

Variables are called variables because they can vary: you can store a new value in one at any time with =. The old value is thrown away and replaced.

#include <stdio.h>

int main(void) {
    int hp = 100;
    printf("Start: %d\n", hp);
    hp = hp - 27;
    printf("After a hit: %d\n", hp);
    hp = 100;
    printf("Healed: %d\n", hp);
    return 0;
}
Start: 100
After a hit: 73
Healed: 100

= is not "equals"

In math, hp = hp - 27 would be impossible. In C, = means assign: "work out the value on the right, then store it in the box on the left". So hp = hp - 27 runs in two stages:

  1. Read the current value of hp (100) and subtract 27, giving 73.
  2. Store 73 into hp, replacing 100.

The right side is always worked out completely before anything is stored, which is why a variable can appear on both sides.

Declaring vs assigning

int hp = 100; creates the box (with its type) and fills it. Later lines just write hp = ...; without int. Writing int hp again in the same place would try to create a second box with the same name, and the compiler reports redefinition of 'hp'.

Your task

The player has 3200 money and buys a rifle for 2700. Subtract the price from money so the program prints Money left: 500.

Challenge 2

The player starts with 100 HP, takes 27 damage, then picks up a medkit that heals 15. Change hp for each event so the program prints HP: 88.

Challenge 3

The same variable changes three times, and the program prints it after each change. Starting from 800, add the round win reward of 3250, then buy a rifle for 2700, then buy armor for 650. The output should be:

After win: 4050
After rifle: 1350
After armor: 700

Previous: Printing values with %d Next: Decimals with double