1.4 — Variables: a labeled box

📘 Chapter 1⏱ about 2 min read✍️ Beginner friendly
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:

TypeHoldsExample
intwhole numbers42
doublenumbers with decimals3.14
charone single character'A'
booltrue or falsetrue
std::stringtext"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.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.