Explain it simply
Explain it simply
A variable is a named piece of memory that holds one value of one type. When you write int age{20};, you ask for a slot big enough for an int, label it age and put 20 in it. Later you can read the value, print it or replace it with a new one, but the type stays int for the variable's whole life.
The type is the part that surprises people coming from Python or JavaScript. In C++ a variable cannot hold a number now and text later. That rule lets the compiler catch mistakes early, and it lets it pick exactly the right amount of memory and the right machine instructions for each value.
Problem → Why → Solution
The problem: values that quietly change or were never set
Two bugs show up in almost every beginner's first C++ programs. The first is a variable declared without a value and then used: a local int with no initializer holds whatever bits were left in that memory, so a running total can start from some random number. The second is a value that changes as it is stored: put 19.99 into an int and you get 19, with no error message unless you ask for extra warnings.
#include <iostream>
int main() {
int total; // no value yet: reading it is undefined behavior
total += 5;
int price = 19.99; // compiles: the .99 is silently dropped
std::cout << total << ' ' << price << '\n';
}Why does C++ allow this?
C++ inherited C's rule that local variables of built-in types are not set to zero automatically, because zeroing costs time and the language avoids hidden work. It also inherited C's implicit conversions, so a double can be squeezed into an int. With -Wall, GCC does warn that total is used uninitialized, but the price line passes -Wall -Wextra silently; only -Wconversion reports it. The modern fix is to always initialize, and to use braces, which turn the price line into a compile error.
Core concept: declare, initialize, then use
A declaration names a type and a variable: int lessons; An initializer gives it its first value in the same statement. C++ has several spellings for that, and you will meet all of them in real code: int a = 5; (copy initialization, from C), int b(5); (direct initialization) and int c{5}; (brace or list initialization, added in C++11). For simple types they all produce the same value.
Braces are the modern default for one reason: they refuse narrowing conversions, which lose information. int price{19.99}; does not compile; GCC reports "narrowing conversion of '1.9989999999999998e+1' from 'double' to 'int'". That odd number is how GCC prints the double closest to 19.99, a hint that the value was never exact in the first place. Empty braces value-initialize: int count{}; is guaranteed to start at 0.
auto asks the compiler to deduce the type from the initializer: auto lessons = 35; is an int and auto ratio = 0.5; is a double. auto requires an initializer, so it also protects you from uninitialized variables. Be careful with text: auto name = "Thuta"; deduces const char*, a pointer to characters, not std::string.
const makes a variable read-only after initialization; assigning to it later is a compile error. constexpr goes further: the value must be known at compile time, so constexpr int maxSeats{40}; can be used where the compiler needs a constant, such as an array size. Use const for values computed while the program runs and constexpr for fixed constants.
Initialization and assignment are different operations that look alike. int score{70}; creates the variable and gives it its first value, while score = 80; replaces the value of a variable that already exists. That difference is why a const variable can be initialized but never assigned. For class types such as std::string the two jobs are also separate pieces of code. Giving the real value at the point of declaration is therefore simpler, and often faster, than creating an empty variable and filling it in afterwards.
- Type picks the box's size and shape
- The name is the label you refer to
- The initializer fills it right away
- const seals the lid after filling
A box with no initializer is not empty; it holds leftover bits.
General pattern: declaring variables
Type name{value}; // brace initialization (preferred)
Type name = value; // copy initialization
Type name{}; // value-initialized: 0, 0.0, false, ""
auto name = value; // type deduced from the value
const Type name{value}; // read-only after initialization
constexpr Type name{value}; // must be known at compile time
name = newValue; // assignment: replace the value laterEvery declaration has a type (or auto) and a name, and should have an initializer. The last line is not a declaration: an assignment without a type replaces the value of a variable that already exists.
Example: Thuta's profile
This program initializes seven variables of different types with braces, including one constexpr constant and one auto variable. It prints a bool once the default way and once with std::boolalpha, and finally changes a value with an assignment. Predict all six output lines, especially the two bool lines.
#include <iostream>
#include <string>
int main() {
std::string name{"Thuta"};
int age{20};
double height{5.8};
char grade{'A'};
bool isLearning{true};
constexpr int passMark{50};
auto lessonsDone = 4; // deduced as int
std::cout << name << " is " << age << " years old.\n";
std::cout << "Height: " << height << '\n';
std::cout << "Grade: " << grade << '\n';
std::cout << "Learning C++: " << isLearning << '\n';
std::cout << std::boolalpha << "Learning C++: " << isLearning << '\n';
lessonsDone = lessonsDone + 1; // assignment replaces the value
std::cout << "Lessons done: " << lessonsDone << ", pass mark: " << passMark << '\n';
return 0;
}Code breakdown
- Line 5
std::string name{"Thuta"};Braces work for class types such as std::string too. The <string> header must be included.
- Line 8
char grade{'A'};Single quotes make one character. With double quotes, char grade{"A"}; fails to compile, because "A" is a string literal.
- Line 10
constexpr int passMark{50};A fixed value known at compile time. Writing passMark = 60; later is a compile error.
- Line 11
auto lessonsDone = 4;4 is an int literal, so lessonsDone is an int. auto is not a dynamic type: the type is decided once, on this line, and never changes.
- Lines 16-17
std::cout << std::boolalpha << "Learning C++: " << isLearning << '\n';By default std::cout prints a bool as 1 or 0. Sending std::boolalpha once makes later bools print as true and false; the setting stays on std::cout.
- Line 19
lessonsDone = lessonsDone + 1;An assignment, with no type. The right side is evaluated first (4 + 1) and the result, 5, goes back into the box.
Thuta is 20 years old.
Height: 5.8
Grade: A
Learning C++: 1
Learning C++: true
Lessons done: 5, pass mark: 50Comparing the initialization forms
| Form | Example | Putting 2.5 into an int |
|---|---|---|
| Copy | int a = 2.5; | Compiles; a becomes 2 |
| Direct | int b(2.5); | Compiles; b becomes 2 |
| Brace | int c{2.5}; | Narrowing compile error |
| Empty braces | int d{}; | No value needed: d is 0 |
GCC only warns about narrowing from a variable
The standard makes every narrowing inside braces ill-formed. GCC, though, gives an error when the source is a constant like 2.5 but only a warning for a variable, as in double price{1.5}; int whole{price};. Compile with -Werror and that warning becomes an error too, so with this course's -Wall -Wextra -Werror command every narrowing stops the build.
Naming rules and scope
- Names may contain letters, digits and underscores but cannot start with a digit: 2ndPlace is invalid, secondPlace is fine.
- C++ is case-sensitive: score and Score are two different variables.
- Keywords such as int, class, new and return cannot be used as names.
- Avoid names containing a double underscore or starting with an underscore and a capital letter; they are reserved for the compiler and library.
- Pick camelCase or snake_case and use it consistently across a project.
A variable lives from the line that declares it to the closing brace of its block; that region is its scope. Below, bonus is declared in an inner block, so using it after the block makes GCC report "'bonus' was not declared in this scope". Declare variables as close as possible to where you first use them.
#include <iostream>
int main() {
int score{70};
{
int bonus{5}; // bonus exists only inside these braces
score = score + bonus;
}
// bonus is gone here: using it would be a compile error
std::cout << "Score: " << score << '\n';
return 0;
}In real projects
Variables in real codebases
Professional code uses const by default: every value that never changes after initialization is marked const, so a reader only has to track the few variables that do change. Configuration constants such as buffer sizes, retry limits and timeouts are written with constexpr, replacing the #define macros found in older code, because a constexpr variable has a type and a scope.
auto is used where type names get long, such as iterators and std::chrono durations, while explicit types stay where they carry meaning, such as int or double. The C++ Core Guidelines rule ES.20, "Always initialize an object", is checked automatically by tools such as clang-tidy's cppcoreguidelines-init-variables check, and many teams run those checks in continuous integration.
Common mistakes
Common mistakes with variables
1. Reading a variable before giving it a value
Compile int total; total += 5; with -Wall and GCC warns "'total' is used uninitialized". With warnings off, the program simply carries on with a random number. Writing int total{}; makes it start at 0.
2. Mixing up single and double quotes
char grade = "A"; fails with "invalid conversion from 'const char*' to 'char'", because double quotes make a string literal. The reverse, std::string name = 'Thuta';, gives a multi-character literal warning and a conversion error. Use 'A' for one character and "Thuta" for text.
3. Expecting auto to give you a std::string
After auto name = "Thuta";, try name + " Aung": GCC reports "invalid operands of types 'const char*' and 'const char [6]' to binary 'operator+'", because two pointers cannot be joined with +. When you want text you can grow and join, write the type: std::string name{"Thuta"};.
4. Relying on std::string without #include <string>
With GCC, <iostream> happens to pull in <string>, so a program that uses std::string without including it may compile. The standard does not guarantee this, so it can break with another compiler or library version. Include the header for everything you use.
Best practices
Best practices
- Initialize every variable where you declare it; use {} when the real value comes later.
- Make brace initialization your default so the compiler catches narrowing.
- Mark values that never change const, and compile-time constants constexpr.
- Give names that say what they hold, such as score or totalPrice; keep names like x, temp and data for tiny scopes.
Mini challenge
Mini challenge: a tea shop order
Declare the variables for one tea shop order and print the total including tax. Then change the quantity and print it again.
- A constexpr tax rate (the double 0.05) and a const std::string item name
- An int quantity and a double unitPrice, both initialized with braces
- An auto subtotal computed from quantity * unitPrice, then print the total including tax
- Change quantity with an assignment, recompute subtotal and print again
#include <iostream>
#include <string>
int main() {
// TODO: constexpr tax rate 0.05 and a const std::string item name
// TODO: quantity (int) and unitPrice (double), both with braces
// TODO: auto subtotal = ...; print "<item> x<quantity> = <total with tax>"
// TODO: assign a new quantity, recompute subtotal, print again
return 0;
}Expected: With Milk tea at a unit price of 1.50: Milk tea x2 = 3.15 Milk tea x4 = 6.3
Show hint
int * double gives a double, so auto makes subtotal a double. The total with tax is subtotal * (1 + taxRate). Try assigning to the const item later and see what the compiler says.
Show solution
#include <iostream>
#include <string>
int main() {
constexpr double taxRate{0.05};
const std::string item{"Milk tea"};
int quantity{2};
double unitPrice{1.50};
auto subtotal = quantity * unitPrice; // int * double gives a double
std::cout << item << " x" << quantity << " = " << subtotal * (1 + taxRate) << '\n';
quantity = 4; // assignment: new value, same type
subtotal = quantity * unitPrice;
std::cout << item << " x" << quantity << " = " << subtotal * (1 + taxRate) << '\n';
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A variable has one fixed type, a name and a value; the type never changes.
- Brace initialization refuses narrowing and {} gives 0; reading an uninitialized local is undefined behavior.
- auto deduces the type from the initializer, and "text" gives const char*, not std::string.
- const means read-only at run time; constexpr requires a value known at compile time.
The Current ISO C++ Standard (C++23) — Standard C++ Foundation