Loading lessons...
Object Sizes and sizeof
Object Sizes and sizeof
Every object takes up memory, and the amount matters. C++ gives you a tool to ask exactly how much: the sizeof operator.
sizeof returns bytes
sizeof tells you how many bytes an object or type uses. You can ask about a variable or a type:
cout << sizeof(int); // how big is an int? (4 on most machines)
cout << sizeof(double); // how big is a double? (8)
cout << sizeof(x); // how big is variable x?
sizeof(type)- a size with parentheses around the type.sizeof(variable)- works on a variable too, parentheses optional.
The result is a size_t (that unsigned count type we met earlier).
A typical result
On a modern 64-bit machine, you'll often see:
| Type | sizeof |
|---|---|
bool | 1 |
char | 1 |
int | 4 |
float | 4 |
double | 8 |
Why sizes can vary
The C++ standard sets minimum sizes, not exact ones. A long might be 4 bytes on one machine and 8 on another; an int is at least 2 bytes and usually 4. That's why sizeof exists - instead of guessing, ask.
#include <iostream>
using namespace std;
int main() {
cout << "int is " << sizeof(int) << " bytes" << endl;
return 0;
}
sizeof is compile-time
sizeof is evaluated while compiling, not while running. The answer is baked into the program as a constant - no runtime cost at all.
TL;DR
sizeofreturns the size of a type or variable in bytes.sizeof(int)gives the bytes of an int;sizeof(x)works on a variable.- Typical sizes:
int4,double8,charandbool1. - Sizes vary by machine - the standard only sets minimums.
sizeofis computed at compile time.