Creating Variables
Programs need to remember values: a score in a game, the price of a purchase, a player's name. For that, they use variables. A variable is like a box with a label: it has a name, and it holds a value that you can use later. In C++, every variable also has a data type, which decides what kind of values you can store in it.
You create a variable like this:
int score = 25;intis the data type. It means a whole number (an integer). You'll meet other data types soon.scoreis the name of the variable. You choose it yourself.=stores the value on its right in the variable on its left.25is the value that the variable gets.- The semicolon
;ends the statement, just like in statements withstd::cout.
Creating a variable is called a declaration. And watch out: in programming, the = sign doesn't mean “equals” as in math. Read it as “store”: 25 is stored in the variable score.
To use the value, write the name of the variable. This program prints it:
#include <iostream>
int main() {
int score = 25;
std::cout << score << "\n";
}This prints:
25Rules for the names of variables:
- A name can contain letters, digits and the underscore
_, but it can't start with a digit:player2is fine,2playerisn't. - A name can't contain spaces. If it has more words, write them together and start each word after the first with a capital letter:
highScore,ticketPrice. This style is called camelCase, because the capitals in the middle look like a camel's humps. This course uses it for all names. - Use only plain English letters, without accents:
cafe, notcafé. The compiler might accept accents, but programmers don't use them in names. You could easily writecafeone time andcaféanother, and for C++, those are two different names. - Uppercase and lowercase letters matter:
ageandAgeare two different names. - A name can't be a word that already means something in C++, such as
intorreturn.
Choose names that say what the variable holds: highScore tells you more than h or x.
You can use a variable only after you've created it, and only under exactly the same name. If you get the name wrong, the program doesn't compile:
#include <iostream>
int main() {
int age = 15;
std::cout << Age << "\n";
}The compiler reports:
main.cpp:5:18: error: use of undeclared identifier 'Age'; did you mean 'age'?Line 5 uses the name Age, but there is no variable with that name. An undeclared identifier is a name that nobody has declared (created). The compiler even suggests that you probably meant age.
Instructions
- 1
Below the existing code, create a variable of type
intnamedagewith the value15. - 2
On the next line, print the value of
age. The program should print:25 15