What is a variable?
A variable is a named place in the computer's memory where you keep a value, so you can use it later.
Think of it like this: A variable is like a labelled box. The label is the name (
age), and inside the box is the value (25). In C++ every box also has a type: a box made for whole numbers can only hold whole numbers.
Creating a variable
To create a variable you write its type, its name, and (usually) a starting value:
#include <iostream>
using namespace std;
int main() {
int age = 25;
cout << "My age is " << age << "\n";
return 0;
}Output
My age is 25
intis the type: a whole number (integer).ageis the name we chose.= 25puts the value 25 into the box.- When we print
age(no quotes!), C++ prints the value inside:25.
Changing a variable
A variable can change – that's why it is called variable. Use = again to put a new value in. The old value is thrown away:
#include <iostream>
using namespace std;
int main() {
int score = 10;
cout << "Score: " << score << "\n";
score = 50; // no "int" this time: the box already exists
cout << "Score: " << score << "\n";
score = score + 5; // take the old value, add 5, store it back
cout << "Score: " << score << "\n";
return 0;
}Output
Score: 10 Score: 50 Score: 55
Remember: You write the type (
int) only once, when you create the variable. After that you just use its name.
Many variables
#include <iostream>
using namespace std;
int main() {
int apples = 3;
int oranges = 5;
int total = apples + oranges;
cout << "Fruit in the bowl: " << total << "\n";
return 0;
}Output
Fruit in the bowl: 8
Common mistake: Using a variable before giving it a value.
int x; cout << x;prints a random leftover number from memory. Always give your variables a starting value.