How Big Is a Variable? (sizeof)
Every type takes up a fixed amount of memory.
2 minute read
Big idea
Every type uses a fixed amount of memory, and sizeof tells you how much.
The idea
Memory is measured in bytes. sizeof(type) gives the number of bytes that type takes up.
Example
#include <stdio.h>
int main(void) {
printf("char: %zu\n", sizeof(char));
printf("int: %zu\n", sizeof(int));
printf("float: %zu\n", sizeof(float));
return 0;
}output
char: 1
int: 4
float: 4Run and edit it in the app.
(The sizes are what most computers use today.)
%zu is the format code for printing a size.
Think of it like
Parking spaces. A motorbike (char) takes 1 space, a car (int) takes 4. sizeof counts the spaces.
🕷️ Spidey-sense: My spidey-sense tells me how big a threat is before I swing in.
sizeofis your version: it tells you how many bytes something takes before you use it. Sizes can change between computers — so ask, don't guess.
Why it matters
A char is always exactly 1 byte. Other sizes can differ between computers — which is exactly why you ask sizeof instead of guessing. You'll need it later when you ask for memory yourself.
"With great power comes great responsibility." — Uncle Ben
This is C's deal with you. Most languages manage memory behind your back. C hands you the controls: you decide how much memory to take, and later you'll give it back yourself. That's the power. Knowing exactly how many bytes you're using — that's the responsibility.
sizeofis where it starts.
Key terms
- Byte — The basic unit of memory.
- sizeof — Tells you how many bytes a type or variable uses.
- %zu — The format code for printing a sizeof result.
Check yourself
What does sizeof(int) tell you?
How many bytes is a char?
Which format code prints the result of sizeof?