Variables and Data Types
C++ is statically typed: every variable has a type that is fixed when it is declared and checked by the compiler before your program ever runs.
Declaring Variables
A variable declaration reserves memory of a specific size and gives it a name. You can declare and assign in one step, or declare first and assign later. The compiler will reject any attempt to store a value of the wrong type in a variable.
int age = 25;
double price = 19.99;
char grade = 'A';
bool isEnrolled = true;
std::string name = "Thabo";
std::cout << name << " is " << age << " years old." << std::endl;
Common Built-In Types
Choosing the right type matters for both correctness and memory efficiency. The table below covers the types you will use in almost every program.
- int — whole numbers, typically 4 bytes (e.g. -2, 0, 42).
- double — decimal numbers with high precision (e.g. 3.14159).
- float — decimal numbers with less precision, uses less memory than double.
- char — a single character, stored in 1 byte (e.g. 'A').
- bool — true or false only.
- std::string — text of any length (requires
#include <string>).
Constants
Use const when a value should never change after it is set. This protects against accidental reassignment and communicates intent to anyone reading your code.
const double PI = 3.14159;
const int MAX_STUDENTS = 30;
// PI = 3.2; // Compile error — cannot reassign a const
Common Mistakes
- Trying to store a decimal value in an
int, which silently truncates the fractional part. - Forgetting to
#include <string>before usingstd::string. - Using single quotes for a multi-character value —
'AB'is invalid forchar, which holds exactly one character. - Naming variables with reserved keywords like
intorclass.
Professional Tip
Prefer double over float unless you have a specific memory constraint. The extra precision avoids subtle rounding bugs in calculations, and on modern hardware the performance difference is negligible.
Your Turn
Declare variables to store a student's name, age, GPA (as a double), and whether they are on the honour roll (as a bool). Print a sentence that uses all four values.
Mini Quiz
Which data type would you use to store a value like true or false?
bool stores exactly one of two values: true or false, and is the natural type for yes/no conditions.