1.4 — Variables: a labeled box
Read one box at a time. No rush.
A box with a name#
A variable is a box in memory that holds a value. It has a name so you can use it later.
C++
int age = 12;int= the type. What kind of thing the box holds (here: a whole number).age= the name of the box.= 12= the value we put in.
Using a variable#
Write the name, and C++ uses the value inside.
C++▶ Run
#include <iostream> int main(){ int age = 12; std::cout << "I am " << age << " years old.\n"; return 0;}Output
I am 12 years old.Every box has a type#
In C++, you must say what type a variable holds. Here are the most common:
| Type | Holds | Example |
|---|---|---|
int | whole numbers | 42 |
double | numbers with decimals | 3.14 |
char | one single character | 'A' |
bool | true or false | true |
std::string | text | "hello" |
C++
int lives = 3;double price = 4.99;char grade = 'A';bool isGameOver = false;std::string name = "Sam"; // needs #include <string>Key idea
The type never changes. A box made for int always holds whole numbers.
Object
In C++, a piece of memory that holds a value is called an object. A variable is simply an object with a name.
Making many at once#
You can make several variables of the same type in one line:
C++
int a = 1, b = 2, c = 3;Good habit
Make one variable per line. It is easier to read and harder to get wrong.
Tip: press ← / → to move between lessons, / to search.