Using the sizeof operator
What you'll learn: How to use the sizeof operator to determine exactly how much memory a specific data type occupies on your computer.
The problem with assumptions
In many languages, an integer is just an integer. But in C, the language lives very close to the hardware. Because different computers have different architectures (like 32-bit vs. 64-bit systems), the amount of memory a int or a long uses can actually change depending on where the code is running.
Imagine you are buying storage bins for a warehouse. If you order "standard bins" without checking their measurements, you might find they are too small for your items or too large for your shelves. In C, you never want to guess the size of your "bins." You want to measure them.
Measuring memory with sizeof
The sizeof operator is your digital measuring tape. When you apply it to a data type or a variable, it tells you how many bytes of memory that item occupies. One byte is typically 8 bits of information.
To use it, you place the name of a type inside parentheses after the word sizeof. The result is a number representing the size.
#include <stdio.h>
int main() {
// We use %zu as the format specifier for sizes
printf("Size of a char: %zu byte\n", sizeof(char));
printf("Size of an int: %zu bytes\n", sizeof(int));
printf("Size of a long: %zu bytes\n", sizeof(long));
double myPi = 3.14;
printf("Size of my variable: %zu bytes\n", sizeof(myPi));
return 0;
}
Why this matters
You might notice that on your laptop, an int is 4 bytes, but on a tiny micro-chip inside a microwave, it might only be 2 bytes.
Using sizeof makes your code "portable." If you write a program that needs to know how much space it is using, sizeof ensures the program calculates that value correctly regardless of which computer it is running on. Instead of hard-coding the number "4," you tell C to "go measure it for me." This prevents memory errors and keeps your programs efficient and flexible.
Key takeaway
The sizeof operator provides the size of a type or variable in bytes, ensuring your code adapts to different hardware automatically.