sizeof
- C course
- Beginner
- Lesson 16/116
- 4 min
Learn type sizes with the sizeof operator.
The sizeof operator
The sizeof operator tells how many bytes a type or variable takes in memory. The result has type size_t:
printf("%zu", sizeof(int));
// Output (typically): 4The result can vary by platform, so use %zu instead of %d. sizeof is computed at compile time, with no runtime cost.
What is sizeof for?
sizeof is used for three main purposes:
- Portability: write code based on the type (e.g.,
malloc(sizeof(int) * n)) - Error prevention: avoids copying with the wrong byte count
- Documentation: shows the type's size to the reader
Writing sizeof(int) instead of hardcoding 4 or 8 keeps your code portable across platforms.
Practice Print type sizes
Add two printf calls to the program below: one printing sizeof(int) and the other sizeof(double) with %zu. The output should be int: 4\ndouble: 8.
Starter code
#include <stdio.h>
int main(void) {
// print type sizes with sizeof
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
printf("int: %zu\n", sizeof(int));
printf("double: %zu", sizeof(double));
return 0;
}Expected output
int: 4 double: 8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which specifier for sizeof result?
- %zu Correct answer
- %s
- %c
- %d
Explanation: sizeof returns a size_t; print it with %zu.
2 sizeof usage
printf("%zu", ____);
printf("%zu", sizeof(int));
Explanation: sizeof(int) returns the size of the int type.
3 Match sizeof concepts
| Term | Meaning |
|---|---|
sizeof |
Size operator |
size_t |
Size type |
%zu |
Size specifier |
4 |
int size |