Variables

A variable is a named place in memory where your program keeps a value. You can think of it as a box with a label on it.

To create a variable, write its type, its name, and a starting value:

int score = 10;

int is the type. It means the box holds a whole number. score is the name, and 10 is the value that goes into the box. You will meet more types in the next lesson.

After that line, writing score means "the value in the box right now". You can also put a new value into the box with =. The old value is then gone:

#include <iostream>
using namespace std;

int main() {
    int score = 10;
    cout << score << "\n";
    score = 25;
    cout << score << "\n";
    return 0;
}

Output:

10
25

The two lines that set score look alike, but they do different jobs. int score = 10; has a type in front. It is a declaration: it creates the box. score = 25; has no type. It is an assignment: it changes the value in a box that already exists. You declare a variable once, and after that you can assign to it as often as you like.

Using variables together

You can use variables in a calculation, and you can declare several variables of the same type on one line, with commas between them:

int apples = 3, pears = 4;
cout << apples + pears << "\n";

Output:

7

apples + pears adds the two values. The Operators lesson shows the other calculations you can do.

Naming rules

A name can use letters, digits and the underscore _. It cannot start with a digit, and it cannot be a word that C++ already uses, like int or return. Upper and lower case are different, so score and Score are two different variables.

This course writes names in camelCase: the first word in lower case, and each new word starts with a capital letter, like playerName or totalPrice. Choose names that say what the value is. totalPrice is much easier to understand than x.

Always give a starting value

C++ lets you write int score; with no value. But then C++ does not put 0 in the box for you, and you cannot know what is inside. Reading such a variable is a common bug. Give every variable a starting value when you declare it.

In the exercise, give two variables their values and let the program print their total.