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
intvariable calledapplesset to5.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
doublecalledpriceset to2.5, and print it on its own line.Create a
charcalledgradeset to'B', and print it on its own line.Create a
boolcalledsunnyset totrue, and print it. You should see1.
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::stringcalledcityset to"Paris".Print
I live in Parisusingcity.
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
scoreto10(nointthis time).Then print
scoreagain.
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 intcalledMAX_LIVESset to3.Print
Lives: 3usingMAX_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, anint ageand adouble heightwith any values you like.Print
Name:and thennameon one line, andAge:and thenageon the next.Print
Height:and thenheighton the third line.
More in C++ Basics
Previous: Hello, World! · Next: Operators