Learn C++ · lesson 2 of 61 · about 6 minutes
Variables
Keep your hero's health and gold in int variables, and change them as the game goes on.
What you'll learn
- Make a variable with a type
- Use int for whole numbers and double for decimals
- Change a value with =
Keep score
Every game has numbers that change: health, gold, score. You can't type them into each message, because they change while the game runs. Keep each one in a variable: a value with a name.
In C++ you say what type of value a variable holds when you make it:
intholds whole numbers, like100or-12doubleholds numbers with a decimal point, like1.5
Health and gold
#include <iostream>
int main() {
int health = 100;
int gold = 5;
std::cout << "Health: " << health << ", Gold: " << gold << "\n";
}Output
Health: 100, Gold: 5Values change
Once a variable exists, = gives it a new value, and the old one is gone. Here = stores a value: it doesn't ask whether two things are equal.
health = health - 30; works out the right side first, using the old value, then stores the answer.
Step through it to watch health change
#include <iostream>
int main() {
int health = 100;
health = health - 30;
health = health + 20;
std::cout << "Health: " << health << "\n";
}Output
Health: 90Tip
Write the type only once, when you make the variable. After that, use just the name: writing int health a second time would make another variable with the same name, and the compiler stops you.
Now try it yourself
This lesson is free in Codiqo, with 8 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.