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:
- Read the current value of
hp(100) and subtract 27, giving 73. - 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 turn: the player has 3200 money and buys a rifle for 2700. Subtract the price from money so the program prints Money left: 500.
Previous: Printing values with %d Next: Decimals with double