← C++ from Scratch Lesson 5 of 62 · 10 XP

Variables

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A variable is a named memory cell. In C++ every variable has a type, and it's set once:

int hp = 100;            // an integer
double speed = 2.5;      // a fractional number
char grade = 'A';        // one character
bool alive = true;       // yes/no
std::string name = "Kai"; // a string (#include <string>)

hp = hp - 30;            // assign a new value
const int MAX_HP = 100;  // a constant: it can't be changed, the compiler won't allow it
auto lvl = 5;            // auto — the compiler works out the type (int here)

Names: letters, digits and _, not starting with a digit, no spaces. A variable without an initial value contains garbage — always initialise: int score = 0; or int score{}; (curly braces mean "set to zero").

Task. A hero with 100 health took a hit of 35 and drank a potion worth 20. Create a variable hp, change it and print HP: 85.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.