C++ Variables and Data Types

Store values in typed variables, use strings and constants, and read user input with cin.

Lesson 2 of 44Beginner18 min read

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:

C++
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

TypeHoldsExample
intwhole numbersint score = 120;
doubledecimal numbersdouble price = 4.99;
charone character, single quoteschar grade = 'B';
booltrue or falsebool done = false;
stringtext, double quotesstring 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:

C++
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

C++
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:

C++
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:

C++
cout << sizeof(char) << endl;     // always 1
cout << sizeof(int) << endl;      // 4 on almost every computer today
cout << sizeof(double) << endl;   // 8

The 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.

C++
int lives{3};
int zero{};          // empty braces give 0
int bad = 3.7;       // compiles, quietly becomes 3
int error{3.7};      // compile error: narrowing conversion

With =, 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, bool and std::string.
  • const values can't change; auto lets the compiler infer the type.
  • cin >> x reads one value; getline(cin, s) reads a whole line.
  • Dividing two ints gives an int; use a double or static_cast for decimals.

C++ Variables Examples

Each example shows the code, the output it produces and what each part does.

Example 1

A player profile

C++
#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;
}
Output
Kai (level 7)
Health: 82.5
Rank: S
Online: 1
Online: true
Line-by-line explanation
  1. Lines 6 to 10One variable of each core type.
  2. Line 15By default, cout prints true as 1.
  3. Line 16boolalpha switches cout to printing true and false as words.
Example 2

Reading input

Here the user typed Rosa Diaz and then 19.

C++
#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;
}
Output
Full name: Rosa Diaz
Age: 19
Hi Rosa Diaz, in 5 years you'll be 24.
Line-by-line explanation
  1. Line 10getline reads the whole line, including the space between the names.
  2. Line 12cin >> reads a single int.
  3. Line 14age + 5 is calculated before it's printed.
Example 3

Averages and casting

C++
#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;
}
Output
Total: 61
Wrong average: 15
Right average: 15.25
Line-by-line explanation
  1. Line 5A constant for the number of tests.
  2. Line 9int / int gives an int, so the .25 is lost.
  3. Line 10Casting total to double first keeps the decimals.

Common C++ Variables Mistakes

Using a variable that has no value

Don't
int score;
cout << score;   // prints a random number
Do
int score = 0;
cout << score;

Reading a full name with cin >>

Don't
string name;
cin >> name;   // "Rosa Diaz" stores only "Rosa"
Do
string name;
getline(cin, name);

cin >> stops at the first space.

Single quotes around a string

Don't
string city = 'Paris';
Do
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.

Fill in the blankseasy

Complete the declarations.

 lives = 3;
 hero = "Nova";
Predict the outputeasy

What does this print?

int a = 10;
a = a + 5;
a = a * 2;
cout << a;
Predict the outputmedium

What does this print?

int x = 7;
int y = 2;
cout << x / y << " " << (double)x / y;
Multiple choicemedium

Which line reads a full sentence, including spaces, into s?

Predict the outputmedium

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.

  1. Which type holds true or false?

    • int
    • char
    • bool
    • string
  2. What does const do?

    • Makes a variable faster
    • Prevents the value from being changed after it's set
    • Makes the variable global
    • Converts the value to a string
  3. What does auto x = 2.5; create?

    • A double
    • An int
    • A string
    • A variable with no type
  4. Why might getline return an empty string right after cin >> 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
  5. How do you read a whole line, including spaces, into a string?

    • getline(cin, line);
    • cin >> line;
    • cin.read(line);
    • readline(line);