A variable is a named piece of memory that holds a value. In C++ you must say what type of value each variable holds when you create it: a whole number, a decimal, a single character, true or false, or text. The compiler uses that type to reserve the right amount of memory and to catch mistakes.
Programs also need to get information from people. In C++, cin reads what the user types on the keyboard, the mirror image of cout.
In this lesson you'll declare variables of the core types, work with std::string, create constants, read input with cin and getline, and convert between types.
Declaring variables
Write the type, then the name, and optionally a starting value:
int age = 16;
double height = 1.74;You can change a variable later with =: age = 17;. Always give variables a starting value. In C++, a local variable without one contains whatever happened to be in that memory, which leads to confusing bugs.
Variable names can use letters, digits and underscores, can't start with a digit, and are case-sensitive.
The core types
| Type | Holds | Example |
|---|---|---|
int | whole numbers | int score = 120; |
double | decimal numbers | double price = 4.99; |
char | one character, single quotes | char grade = 'B'; |
bool | true or false | bool done = false; |
string | text, double quotes | string name = "Kai"; |
string needs #include <string> and lives in the std namespace, so its full name is std::string. Strings have useful functions: name.length() gives the number of characters, and + joins two strings.
const and auto
const makes a value that can't change after it's set. Use it for fixed values such as tax rates or the size of a game board:
const double VAT = 0.2;auto lets the compiler work out the type from the value: auto count = 10; makes an int, and auto ratio = 0.5; makes a double. The variable still has a fixed type; auto only saves typing.
Reading input with cin and getline
int age;
cout << "Age: ";
cin >> age;cin >> reads one value of the variable's type and stops at the first space. To read a whole line of text, including spaces, use getline:
string fullName;
getline(cin, fullName);If you use cin >> and then getline, add cin.ignore(); between them. Otherwise getline reads the leftover Enter key and returns an empty line.
Type sizes and brace initialisation
Each type takes a fixed number of bytes, and sizeof tells you how many:
cout << sizeof(char) << endl; // always 1
cout << sizeof(int) << endl; // 4 on almost every computer today
cout << sizeof(double) << endl; // 8The size limits what a type can hold. A 4-byte int reaches 2,147,483,647, while long long is at least 8 bytes and goes up to about 9.2 quintillion. You can check the exact limits with std::numeric_limits<int>::max() from <limits>.
There's also a second way to give a variable its starting value: braces.
int lives{3};
int zero{}; // empty braces give 0
int bad = 3.7; // compiles, quietly becomes 3
int error{3.7}; // compile error: narrowing conversionWith =, C++ silently chops a double down to fit an int. With braces, the compiler refuses any conversion that could lose information, which turns a hidden bug into an error message you can fix. Many modern style guides prefer braces for this reason, and you'll see both forms in real code.
C++ Variables Syntax
Variables and input
#include <string>
type name = value;
const type NAME = value;
auto x = value;
cin >> variable;
getline(cin, stringVariable);
double d = static_cast<double>(intValue);C++ Variables Summary
- Declare variables as
type name = value;and always initialise them. - Core types:
int,double,char,boolandstd::string. constvalues can't change;autolets the compiler infer the type.cin >> xreads one value;getline(cin, s)reads a whole line.- Dividing two ints gives an int; use a double or
static_castfor decimals.
C++ Variables Examples
Each example shows the code, the output it produces and what each part does.
A player profile
#include <iostream>
#include <string>
using namespace std;
int main() {
string name = "Kai";
int level = 7;
double health = 82.5;
char rank = 'S';
bool online = true;
cout << name << " (level " << level << ")" << endl;
cout << "Health: " << health << endl;
cout << "Rank: " << rank << endl;
cout << "Online: " << online << endl;
cout << boolalpha << "Online: " << online << endl;
return 0;
}Kai (level 7)
Health: 82.5
Rank: S
Online: 1
Online: trueLine-by-line explanation
- Lines 6 to 10One variable of each core type.
- Line 15By default, cout prints true as 1.
- Line 16boolalpha switches cout to printing true and false as words.
Reading input
Here the user typed Rosa Diaz and then 19.
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
cout << "Full name: ";
getline(cin, name);
cout << "Age: ";
cin >> age;
cout << "Hi " << name << ", in 5 years you'll be " << age + 5 << "." << endl;
return 0;
}Full name: Rosa Diaz
Age: 19
Hi Rosa Diaz, in 5 years you'll be 24.Line-by-line explanation
- Line 10getline reads the whole line, including the space between the names.
- Line 12cin >> reads a single int.
- Line 14age + 5 is calculated before it's printed.
Averages and casting
#include <iostream>
using namespace std;
int main() {
const int TESTS = 4;
int total = 15 + 18 + 12 + 16;
cout << "Total: " << total << endl;
cout << "Wrong average: " << total / TESTS << endl;
cout << "Right average: " << static_cast<double>(total) / TESTS << endl;
return 0;
}Total: 61
Wrong average: 15
Right average: 15.25Line-by-line explanation
- Line 5A constant for the number of tests.
- Line 9int / int gives an int, so the .25 is lost.
- Line 10Casting total to double first keeps the decimals.
Common C++ Variables Mistakes
Using a variable that has no value
int score;
cout << score; // prints a random numberint score = 0;
cout << score;Reading a full name with cin >>
string name;
cin >> name; // "Rosa Diaz" stores only "Rosa"string name;
getline(cin, name);cin >> stops at the first space.
Single quotes around a string
string city = 'Paris';string city = "Paris";Single quotes are for one char only, such as 'P'.
C++ Variables in Real Projects
Types and input in practice
Games store positions as double or float, counts as int and names as string. Choosing the smallest suitable type mattered a lot on old hardware and still matters on small devices like smartwatches. Command-line tools read their settings with cin or from files in exactly the way you practised here.
C++ Variables FAQ
What is the difference between float and double in C++?
A float usually takes 4 bytes and keeps about 7 significant digits, while a double takes 8 bytes and keeps about 15 to 16. A decimal literal such as 3.14 is a double; add f (3.14f) to make a float. Use double unless you're storing huge amounts of numbers, as in graphics, where the saved memory matters.
How do I check that cin read a valid number?
Test the stream: if (!(cin >> age)) is true when the user typed something that isn't a number. After a failure, cin refuses all further reads until you call cin.clear() and throw away the bad input with cin.ignore(numeric_limits<streamsize>::max(), '\n'). In modern C++ the variable is set to 0 when the read fails.
What is the difference between const and constexpr?
A const variable can't change after it's set, but its value can come from something worked out while the program runs, such as user input. A constexpr variable must be calculable by the compiler, so constexpr int SIZE = 10; is fine but constexpr int n = readNumber(); is an error unless readNumber is itself constexpr. Use constexpr for true fixed values like array sizes.
Can I declare several variables on one line in C++?
Yes: int wins = 0, losses = 0;. Each variable needs its own starting value, though. int a, b = 0; only sets b to 0 and leaves a uninitialised, which is an easy bug to miss. When the names need different values or comments, one variable per line is clearer.
When should I use unsigned int?
Rarely in beginner code. unsigned int can't hold negative values, and going below zero wraps round to a huge number instead: 0u - 1 is 4294967295. That makes subtraction bugs hard to spot, so use plain int for counts and scores, and save unsigned types for sizes from the standard library and for working with bits.
C++ Variables Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the declarations.
lives = 3;
hero = "Nova";
What does this print?
int a = 10;
a = a + 5;
a = a * 2;
cout << a;
What does this print?
int x = 7;
int y = 2;
cout << x / y << " " << (double)x / y;
Which line reads a full sentence, including spaces, into s?
What does this print?
auto x = 5 / 2;
auto y = 5 / 2.0;
cout << x << " " << y << endl;
C++ Variables Quiz
5 questions to check what you learned.
Which type holds
trueorfalse?- int
- char
- bool
- string
What does
constdo?- Makes a variable faster
- Prevents the value from being changed after it's set
- Makes the variable global
- Converts the value to a string
What does
auto x = 2.5;create?- A double
- An int
- A string
- A variable with no type
Why might
getlinereturn an empty string right aftercin >> age;?- getline only works at the start of a program
- It reads the Enter key left behind by cin >>
- age must be a string
- cin closes after one use
How do you read a whole line, including spaces, into a string?
- getline(cin, line);
- cin >> line;
- cin.read(line);
- readline(line);