Declare and Use Variables in C++
Learn to declare, initialize, and use typed variables in C++ — the building block behind every program you will write.
By the end of this page, you will be able to declare variables of the most common C++ types, initialize them safely using modern syntax, mark values that should never change with const, and recognize the mistakes that trip up almost every beginner.
What and Why
Every program needs to remember things — a player's score, a temperature reading, a username. A variable is a named slot in memory where your program stores one piece of data. Before you can use that slot, you have to tell C++ two things: what the slot is called and what kind of data it will hold.
That second requirement is what makes C++ a statically typed language. The type is not decoration — it determines how many bytes the variable occupies, what operations are legal on it, and what the bit pattern means. Storing a fractional number in a slot meant for a whole number is a mistake C++ catches before your program even runs.
This compile-time checking feels strict at first, but it is one of the things that makes C++ programs reliable. The compiler is your first line of defense against bugs.
Step by Step
1 — Declaring a variable
A declaration names the variable and picks its type. Nothing more.
#include <iostream>
int main() {
int score; // declares an integer variable called score
score = 42; // assigns the value 42 to it
std::cout << score << "\n";
}int is short for integer — a whole number (no decimal point). The line int score; reserves memory; the line score = 42; puts a value there.
Warning: reading an uninitialized variable like
scorebefore assigning to it is undefined behavior — your program may print garbage, crash, or do something worse. Always initialize.
2 — Initializing at the point of declaration
C++ lets you declare and initialize in one step. Prefer this — it eliminates the uninitialized-variable trap entirely.
#include <iostream>
int main() {
int score = 42;
std::cout << score << "\n";
}C++11 introduced brace initialization (also called uniform initialization), which works for every type and is harder to misuse:
#include <iostream>
int main() {
int score {42};
double ratio {3.14};
bool active {true};
char grade {'A'};
std::cout << score << " " << ratio << " " << active << " " << grade << "\n";
}Braces refuse to silently truncate values (e.g., stuffing a double into an int), so the compiler will error rather than lose precision. This is the initialization style you should reach for by default throughout this site.
3 — The most common built-in types
| Type | Meaning | Example literal |
|---|---|---|
int | whole number | 42, -7 |
double | floating-point number | 3.14, -0.5 |
bool | true or false | true, false |
char | single character | 'A', '\n' |
#include <iostream>
int main() {
int apples {5};
double price {1.99};
bool inStock {true};
char rating {'B'};
std::cout << apples << " apples at $" << price << "\n";
std::cout << "In stock: " << inStock << "\n";
std::cout << "Rating: " << rating << "\n";
}4 — Text with std::string
For anything longer than a single character you need std::string from the <string> header.
#include <iostream>
#include <string>
int main() {
std::string name {"Alice"};
std::cout << "Hello, " << name << "!\n";
name = "Bob"; // reassignment works just like int
std::cout << "Hello, " << name << "!\n";
}5 — Constants with const
When a value should never change after initialization, say so with const. The compiler will reject any code that tries to modify it.
#include <iostream>
int main() {
const double kPi {3.14159265358979};
// kPi = 3.0; // error: cannot assign to a const variable
double radius {5.0};
double area {kPi * radius * radius};
std::cout << "Area: " << area << "\n";
}Making values const is not just a safety measure — it documents intent. A future reader (including yourself in six months) immediately knows this value is fixed.
Common Patterns
Pattern 1 — Accumulating a running total
#include <iostream>
int main() {
int total {0};
total = total + 10;
total += 25; // shorthand for total = total + 25
total += 5;
std::cout << "Total: " << total << "\n"; // 40
}The += operator is idiomatic C++ for accumulation loops.
Pattern 2 — Capturing user input
#include <iostream>
#include <string>
int main() {
std::string username;
int age {0};
std::cout << "Enter your name: ";
std::cin >> username;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Hello, " << username << ". You are " << age << " years old.\n";
}std::cin >> reads from the keyboard and stores the result in the variable you give it. The type of the variable tells cin how to parse the input.
Pattern 3 — Computed constants
Group all magic numbers at the top of a function as named constants. This makes the intent clear and the code easy to update.
#include <iostream>
int main() {
const int kSecondsPerMinute {60};
const int kMinutesPerHour {60};
const double kTaxRate {0.08};
int durationMinutes {90};
double itemPrice {49.99};
int durationSeconds {durationMinutes * kSecondsPerMinute};
double totalWithTax {itemPrice * (1.0 + kTaxRate)};
std::cout << durationMinutes << " min = " << durationSeconds << " sec\n";
std::cout << "Price with tax: $" << totalWithTax << "\n";
}What Can Go Wrong
Mistake 1 — Reading before writing
int score;
std::cout << score; // undefined behavior — score has no value yetFix: always initialize at the point of declaration.
int score {0};
std::cout << score; // safe: prints 0Mistake 2 — Integer division surprises
#include <iostream>
int main() {
int a {7};
int b {2};
std::cout << a / b << "\n"; // prints 3, not 3.5
}When both operands are int, / performs integer division and discards the remainder. If you need the fractional part, at least one operand must be a double.
#include <iostream>
int main() {
double a {7.0};
int b {2};
std::cout << a / b << "\n"; // prints 3.5
}Mistake 3 — Narrowing inside braces catches you (intentionally)
double pi {3.14};
int truncated {pi}; // compile error with brace-init — value would be narrowedThis is the brace-initialization safety net working correctly. Either use a double variable or perform an explicit cast to make your intent visible:
int truncated {static_cast<int>(pi)}; // explicit: you mean to drop the decimalMistake 4 — Forgetting the std:: prefix
string alone does not work — you either need std::string or a using namespace std; declaration (which is fine in small examples but avoided in larger programs for clarity).
Quick Reference
| Concept | Syntax | Notes |
|---|---|---|
| Declare + initialize | int x {42}; | Prefer braces in C++11 and later |
| Reassign | x = 99; | Only for non-const variables |
| Constant | const int x {42}; | Must initialize; cannot reassign |
| Common types | int, double, bool, char, std::string | Need <string> for the last one |
| Accumulate | x += value; | Equivalent to x = x + value; |
| Read input | std::cin >> x; | Parses according to type of x |
All examples on this page require C++11 or later. Compile with -std=c++11 (or any newer flag).
What's Next
With variables and types in hand, the next step is controlling the flow of your program:
- Conditionals and Branching — make decisions with
if,else, andswitch - Loops — repeat actions with
forandwhile - Functions — package logic into reusable, named units
When you are ready to go deeper on the type system itself, the fundamental types reference covers every built-in type, its size guarantees, and the fixed-width alternatives like int32_t.