The Analogy: Choosing the Right Container
Imagine packing a kitchen. You would not store soup in a paper bag or a single grain of rice in a wheelie bin. You pick a container that fits what you are storing: a small jar for spices, a large tub for flour, a sealed bottle for liquid.
C++ types are exactly that decision, made explicit. Every type is a promise about three things: how many bytes it occupies, what range of values it can hold, and what operations make sense on it. Unlike Python or JavaScript, where a number is just "a number", C++ makes you choose the container — and then holds you to it.
That sounds like extra work. In exchange you get speed (the compiler knows exactly how much memory to reserve) and safety (mixing incompatible types is a compile error, not a runtime surprise).
Syntax or Core Structure
#include <iostream>
#include <string>
int main() {
// Integers
int score{42}; // whole numbers, usually 4 bytes
long long big{9000000000}; // when int is not wide enough
unsigned int lives{3}; // no negatives, double the positive range
short small{100}; // smaller footprint, rarely worth it
// Floating point
float ratio{0.5f}; // ~7 digits of precision, note the f suffix
double precise{0.1}; // ~15 digits -- the default choice
// Single characters
char grade{'A'}; // one byte, single quotes
// Truth values
bool passed{true}; // true or false, 1 byte
// Text
std::string name{"Ada"}; // from <string>, double quotes
std::cout << score << " " << ratio << " " << grade << " " << passed << "\n";
return 0;
}
Two details that catch people out immediately: 'A' with single quotes is a char, while "A" with double quotes is a string. And std::cout << passed prints 1, not true — booleans print as integers unless you ask otherwise with std::boolalpha.
Technical Depth: Sizes, Ranges and Overflow
The standard does not fix exact sizes; it fixes minimums. On virtually every desktop and server compiler today you get:
| Type | Typical size | Approximate range | Use it for |
|---|---|---|---|
bool | 1 byte | true / false | flags, conditions |
char | 1 byte | -128 to 127 | single characters, raw bytes |
short | 2 bytes | -32,768 to 32,767 | rarely needed |
int | 4 bytes | about +/- 2.1 billion | default whole number |
long long | 8 bytes | about +/- 9.2 quintillion | ids, timestamps, big counts |
unsigned int | 4 bytes | 0 to about 4.2 billion | sizes, indices, bit patterns |
float | 4 bytes | ~7 significant digits | huge arrays where memory matters |
double | 8 bytes | ~15 significant digits | default real number |
Ask the compiler rather than trusting a table:
#include <iostream>
#include <limits>
std::cout << sizeof(int) << " bytes\n"; // 4 on most systems
std::cout << std::numeric_limits<int>::max() << "\n"; // 2147483647
std::cout << std::numeric_limits<double>::digits10 << "\n"; // 15
Overflow is not an error
int big{2147483647}; // the maximum int
big = big + 1; // undefined behaviour -- typically wraps to -2147483648
unsigned int u{0};
u = u - 1; // WELL defined, and wraps to 4294967295
Signed overflow is undefined behaviour: the compiler may assume it never happens and optimise accordingly, so the result can be genuinely unpredictable. Unsigned overflow is defined to wrap around, which is why for (unsigned i = size - 1; i >= 0; --i) is an infinite loop — an unsigned value is never negative.
Floating point does not store decimals exactly
double a{0.1}, b{0.2};
std::cout << (a + b == 0.3) << "\n"; // prints 0 -- they are NOT equal
// Compare with a tolerance instead
#include <cmath>
bool same = std::abs((a + b) - 0.3) < 1e-9; // true
0.1 in binary is a repeating fraction, exactly like 1/3 in decimal. It gets rounded, and the rounding errors accumulate. Never use == on double. Never store money in a double — use integer cents, or a decimal library.
Conversions happen silently
double price{9.99};
int rounded = price; // 9 -- the fraction is DISCARDED, not rounded
int half = 7 / 2; // 3 -- integer division, the .5 never existed
double proper = 7 / 2.0; // 3.5 -- one operand is double, so both are
int narrowed{price}; // COMPILE ERROR: braces reject narrowing. Good.
Integer division is the single most common silent bug in beginner C++. If either operand is floating point, the whole expression is; if both are integers, the result is truncated toward zero.
Real World Example: A Sensor Reading
#include <iostream>
#include <iomanip>
#include <string>
int main() {
const std::string sensorId{"TEMP-07"}; // text: string
const bool online{true}; // yes/no: bool
const int sampleCount{1440}; // whole count: int
const long long unixTime{1735689600LL}; // too big for int: long long
const double celsius{21.4567}; // real measurement: double
const char unit{'C'}; // one character: char
const double fahrenheit = celsius * 9.0 / 5.0 + 32.0; // 9.0 keeps it floating point
std::cout << std::boolalpha; // print bools as true/false
std::cout << std::fixed << std::setprecision(2); // two decimal places
std::cout << "Sensor: " << sensorId << "\n";
std::cout << "Online: " << online << "\n";
std::cout << "Samples: " << sampleCount << "\n";
std::cout << "Epoch: " << unixTime << "\n";
std::cout << "Reading: " << celsius << unit << " (" << fahrenheit << "F)\n";
return 0;
}
Every type here was chosen for a reason. unixTime needs long long because seconds since 1970 already exceed the range of a 4-byte int for far-future dates and will overflow in 2038. The conversion uses 9.0 / 5.0 rather than 9 / 5 — the latter is integer division and would give 1, silently ruining the maths. std::setprecision from <iomanip> controls display only; the stored double keeps its full precision.
Common Mistakes
- Integer division:
7 / 2is3. Write7 / 2.0when you want3.5. - Comparing doubles with
==. Use a tolerance:std::abs(a - b) < 1e-9. - Storing money in
double. Rounding errors accumulate into real accounting problems. Use integer cents. - Mixing signed and unsigned in comparisons.
if (someInt < vec.size())warns becausesize()is unsigned; theintgets converted and a negative value becomes huge. - Confusing
'A'and"A". Single quotes make achar, double quotes make a string literal. - Assuming
intis 4 bytes everywhere. It is on mainstream desktops, but check withsizeofwhen portability matters. - Using
floatby default.doubleis the standard choice;floatonly pays off in very large arrays or on GPUs.
Best Practices
- Default to
intanddouble. Reach for other types only when you have a concrete reason. - Use braces to initialise:
int n{value};rejects narrowing conversions that=accepts silently. - Prefer signed integers for arithmetic, even for values you expect to be positive; unsigned wraparound causes worse bugs than a negative number does.
- Use
long longfor ids and timestamps rather than discovering the limit in production. - Query the compiler with
sizeofandstd::numeric_limitsinstead of memorising ranges. - Mark values
constthe moment you know they will not change.
Practice Exercises
- Type report: Print the size in bytes and the min and max value for
char,short,int,long long,floatanddoubleusingsizeofandstd::numeric_limits. - Division trap: Write a program that reads two integers and prints their quotient both ways — as integer division and as true division — and explain the difference in a comment.
- Precision hunt: Add
0.1to adoubleten times in a loop and print the result withstd::setprecision(20). Then do the same with afloat. Report which one drifts further from1.0and why.