The Analogy: Labelled Boxes of Fixed Size
In Python, a variable is a sticky label you can move onto anything — a number today, a list tomorrow. In C++, a variable is a box of a fixed size, in a fixed place, with a permanent label. When you write int score;, the compiler reserves exactly four bytes on the stack and calls them score. Those four bytes will hold an integer for as long as score exists, and nothing else.
This is why declaring a type is not bureaucracy. The compiler needs to know how big the box is before it can build the shelf.
Syntax or Core Structure
#include <iostream>
#include <string>
int myNum = 15; // 4 bytes, whole numbers
double myFloat = 5.99; // 8 bytes, decimals
char myLetter = 'D'; // 1 byte, single quotes
std::string myText = "Hello"; // text, double quotes
bool myBoolean = true; // 1 byte, true or false
// Declaration and assignment can be separate...
int x; // declared -- contains GARBAGE, not zero
x = 5; // now assigned
// ...but doing both at once is almost always better
int y = 10;
That comment matters more than it looks. An uninitialised local variable in C++ holds whatever bytes happened to be at that memory address. Reading it is undefined behaviour — the program might print 0, might print 32764, might behave differently in a debug build than a release build.
// Three initialisation syntaxes you will see
int a = 5; // copy initialisation (C style)
int b(5); // constructor initialisation
int c{5}; // brace initialisation -- prefer this one
int d{}; // zero-initialised: guaranteed 0
double bad = 4.9;
int lossy = bad; // compiles, silently truncates to 4
int safe{bad}; // Error: narrowing conversion -- caught!
Brace initialisation is the modern default precisely because of that last pair: it refuses to silently lose data.
Technical Depth: const, constexpr and Scope
const means "this cannot be changed after initialisation", and the compiler enforces it.
const int minutesPerHour = 60;
const double pi = 3.14159265358979;
minutesPerHour = 10; // Error: assignment of read-only variable
// constexpr goes further: the value must be known at COMPILE time
constexpr int bufferSize = 1024;
constexpr double gravity = 9.81;
int arr[bufferSize]; // legal -- the compiler knows the size
const int runtimeValue = getUserInput(); // fine: const, decided at runtime
constexpr int broken = getUserInput(); // Error: not a compile-time constant
The rule of thumb: use constexpr for true constants baked into your program, const for values that are set once but only known while running. Marking things const is free, catches real bugs, and often lets the optimiser generate better code.
Scope and lifetime
A variable exists from its declaration to the closing brace of its block, and then it is gone.
#include <iostream>
int globalCounter = 0; // global: lives for the whole program
int main() {
int outer = 1;
{
int inner = 2;
std::cout << outer << inner; // both visible
} // inner is destroyed here
// std::cout << inner; // Error: 'inner' was not declared
for (int i = 0; i < 3; ++i) {
int perLoop = i * 2; // created and destroyed each iteration
}
// i and perLoop are both gone
return 0;
}
Shadowing is legal and dangerous: an inner int outer = 99; would hide the outer one rather than assign to it. -Wshadow warns about this, which is another reason to compile with warnings enabled.
Naming
int playerScore = 0; // camelCase -- common for variables
int player_score = 0; // snake_case -- also common, matches the standard library
const int MAX_PLAYERS = 4; // SCREAMING_CASE -- traditional for constants
int 2fast = 1; // Error: cannot start with a digit
int class = 1; // Error: reserved keyword
Pick one convention and hold to it. C++ identifiers are case-sensitive, may contain letters, digits and underscores, and may not start with a digit.
Real World Example: A Receipt Calculator
#include <iostream>
#include <string>
int main() {
constexpr double taxRate = 0.20; // fixed business rule
const std::string shopName = "Corner Cafe";
std::string item{};
int quantity{};
double unitPrice{};
std::cout << "Item: ";
std::getline(std::cin, item);
std::cout << "Quantity: ";
std::cin >> quantity;
std::cout << "Unit price: ";
std::cin >> unitPrice;
const double subtotal = quantity * unitPrice;
const double tax = subtotal * taxRate;
const double total = subtotal + tax;
std::cout << "\n--- " << shopName << " ---\n";
std::cout << item << " x" << quantity << "\n";
std::cout << "Subtotal: " << subtotal << "\n";
std::cout << "Tax: " << tax << "\n";
std::cout << "Total: " << total << "\n";
return 0;
}
Notice what is const and what is not. The inputs must be mutable because std::cin writes into them. Everything derived from those inputs is const, because recalculating a total halfway through a function is a bug, not a feature. Marking them const means the compiler will catch that bug for you.
Type Reference
| Type | Typical size | Range or use |
|---|---|---|
bool | 1 byte | true / false |
char | 1 byte | one character, 'a' |
int | 4 bytes | about -2.1 to +2.1 billion |
long long | 8 bytes | very large whole numbers |
float | 4 bytes | ~7 significant digits |
double | 8 bytes | ~15 significant digits |
std::string | varies | text of any length |
Common Mistakes
- Reading an uninitialised variable — it is garbage, and the behaviour is undefined.
- Single quotes for strings:
'D'is achar,"D"is a string literal. They are not interchangeable. - Assigning a
doubleto anintand being surprised that4.9becomes4. Braces catch it;=does not. - Forgetting
#include <string>before usingstd::string. - Shadowing an outer variable and then wondering why the outer one never changed.
- Using a variable outside its block — after the closing brace it does not exist.
- Trying to reassign a
const, or marking somethingconstexprwhose value is only known at runtime.
Best Practices
- Declare and initialise in one step, using braces:
int count{0};. - Make everything
constthat you do not intend to change; loosen it only when the compiler complains. - Use
constexprfor compile-time constants such as buffer sizes and physical constants. - Give variables descriptive names —
elapsedSeconds, nott. - Declare variables in the smallest scope that needs them, as late as possible.
- Prefer
doubleoverfloatfor general arithmetic; the extra precision is almost always worth it.
Practice Exercises
- The Uninitialised: Declare an
intwithout initialising it, print it, and compile with-Wall. Read the warning, then fix it withint x{};. - The Narrowing: Try
int n{3.7};and thenint n = 3.7;. Explain why only one of them compiles. - The Constants: Rewrite the receipt program so that every value which should not change is marked
constorconstexpr, then try to modify one and read the error.