Data Types
Every variable in C++ has a data type that tells the compiler how to interpret the bits stored in memory. C++ provides a small set of fundamental types built into the language, plus ways to build more precise or portable types on top of them.
Fundamental Types
Type | Represents | Typical Size | Example |
|---|---|---|---|
int | Whole numbers | 4 bytes | 42, -7, 0 |
float | Single-precision floating point | 4 bytes | 3.14f |
double | Double-precision floating point | 8 bytes | 3.14159265 |
char | A single character | 1 byte | 'A', '9', '\n' |
bool | true or false | 1 byte | true, false |
void | No value / no type | n/a | used for functions returning nothing |
sizeof(int) >= sizeof(short)) — it does not guarantee that int is exactly 4 bytes on every platform. Never hard-code an assumption about a type's size; use the sizeof() operator to check it on the target platform, or use fixed-width types when the exact size matters.#include <iostream>
int main() {
std::cout << "int: " << sizeof(int) << " bytes\n";
std::cout << "float: " << sizeof(float) << " bytes\n";
std::cout << "double: " << sizeof(double) << " bytes\n";
std::cout << "char: " << sizeof(char) << " bytes\n";
std::cout << "bool: " << sizeof(bool) << " bytes\n";
return 0;
}Fixed-Width Integer Types
int, long, etc. can vary
between compilers and platforms, <cstdint> provides types with a
guaranteed, exact bit width. These are the right choice whenever portability or an
exact memory layout matters — for example in file formats, network protocols, or
embedded programming.
#include <cstdint>
#include <iostream>
int main() {
int32_t id = 100000; // guaranteed exactly 32 bits, signed
uint64_t counter = 0; // guaranteed exactly 64 bits, unsigned
int8_t smallFlag = 1; // guaranteed exactly 8 bits, signed
std::cout << id << " " << counter << " " << (int)smallFlag << std::endl;
return 0;
}int8_t,int16_t,int32_t,int64_t— exact-width signed integersuint8_t,uint16_t,uint32_t,uint64_t— exact-width unsigned integersint_fast32_t,int_least32_t— "at least this wide, whichever is fastest/smallest" variants
A Teaser: Type Deduction with `auto`
auto keyword, which avoids repeating long type names. We cover this
in depth on the dedicated auto & decltype page, but here is a
quick preview:
auto count = 10; // deduced as int auto price = 19.99; // deduced as double auto initial = 'A'; // deduced as char
sizeof(variableName) or sizeof(Type) any time you need to confirm how much memory something actually occupies on your target platform — never assume.