Variables

Programming Languages · C++ Basics · 10 min

Store numbers, letters, text and true/false values in named boxes, and change them.

Boxes with names

A variable is a named box that holds a value. In C++ you also say what type of value goes in the box. int holds whole numbers:

int lives = 3;
std::cout << lives << "\n";

No quotes around lives when you print it: you want what's inside the box, not the word.

  • Create an int variable called apples set to 5.

  • Print apples.

Decimals, letters and true/false

Different boxes for different values:

double price = 4.99;   // numbers with a decimal point
char grade = 'A';      // one character, in single quotes
bool done = true;      // true or false

std::cout prints a bool as 1 for true and 0 for false.

  • Create a double called price set to 2.5, and print it on its own line.

  • Create a char called grade set to 'B', and print it on its own line.

  • Create a bool called sunny set to true, and print it. You should see 1.

Text with std::string

For words and sentences, use std::string. Add #include <string> at the top to use it. The text goes in double quotes:

std::string name = "Ada";
std::cout << "Hi, " << name << "\n";

That prints Hi, Ada: the << arrows glue the pieces together on one line.

  • Create a std::string called city set to "Paris".

  • Print I live in Paris using city.

Changing a value

Variables can change. To put a new value in an existing box, use = without the type:

int score = 0;
score = 10;

Writing int again would try to make a second box with the same name, which is an error.

  • Below the first print, change score to 10 (no int this time).

  • Then print score again.

Values that never change

Some values should never change, like the number of days in a week. Put const in front, and C++ will stop anyone (even you) from changing it by mistake:

const int DAYS_IN_WEEK = 7;
DAYS_IN_WEEK = 8;   // error: it's const!

Many people write constant names in CAPITALS so they stand out.

  • Create a const int called MAX_LIVES set to 3.

  • Print Lives: 3 using MAX_LIVES.

Put it together: a profile card

Make a profile card for anyone you like (you, a pet, a movie hero). Store the details in variables first, then print them from the variables.

  • Create a std::string name, an int age and a double height with any values you like.

  • Print Name: and then name on one line, and Age: and then age on the next.

  • Print Height: and then height on the third line.

More in C++ Basics

Previous: Hello, World! · Next: Operators