C++ Variables and Data Types
Learn C++ variables, fundamental data types, initialization, and common pitfalls like narrowing and overflow.
Second post in the basic C++ series. Data lives in variables, and every variable has a type that tells the compiler how to interpret its bits.
What is a variable?#
A variable is a named piece of memory that holds a value. You must declare its type before using it:
int age = 30;
double price = 19.99;
std::string name = "Ada";
bool done = false;cppFundamental data types#
| Type | Size (typical) | What it holds |
|---|---|---|
bool | 1 byte | true or false |
char | 1 byte | one character, e.g. 'A' |
int | 4 bytes | whole numbers |
double | 8 bytes | floating-point numbers |
void | — | no value (for functions) |
Use int for counts and double for fractional values. Use long, short, and unsigned when you need a different range.
Initialization styles#
C++ offers several ways to initialize a variable:
int a = 5; // copy initialization
int b(5); // direct initialization
int c{5}; // brace initialization (C++11+)
int d{}; // value-initialized to 0cppPrefer brace initialization {}. It rejects narrowing conversions — a value that would lose data — at compile time.
Overflow and narrowing#
short s = 40000; // may overflow: 40000 > max short (32767)
int x = 3.7; // narrowing: 3.7 silently becomes 3cppWith braces these fail to compile instead of silently corrupting data.
Named constants#
Use const for values that must not change:
const double PI = 3.14159;cppconst values are easier to reason about and the compiler can optimize them.
Printing and reading#
#include <iostream>
int main() {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "You are " << age << " years old.\n";
}cppConclusion#
Types define what a variable can hold and what operations make sense. Next in this series: control flow.