sizeof
- C++ course
- Beginner
- Lesson 17/116
- 5 min
Learn type sizes with the sizeof operator.
sizeof
The sizeof operator tells you how many bytes a type or variable occupies in memory. sizeof(int) is typically 4, sizeof(double) is 8, sizeof(char) is always 1.
The syntax is sizeof(type) or sizeof(variable). The result is an integer of type size_t computed at compile time.
sizeof helps portability: since a type's size may vary by system, querying it with sizeof is safer than hardcoding the size.
sizeof with types and variables
sizeof takes both types and variables. sizeof(int) and int x; sizeof(x); give the same result. The size is that of the variable's type.
For arrays, sizeof gives the total bytes: int arr[10]; sizeof(arr) is typically 40 (10 × 4). To find the element count, sizeof(arr) / sizeof(arr[0]) is a common idiom.
For pointers, sizeof gives the pointer size (typically 4 or 8 bytes), not the size of the data it points to. Mind this distinction.
Practice Print sizes with sizeof
Add three std::cout lines inside main: the first prints sizeof(int), the second sizeof(double), the third sizeof(char). End each line with std::endl.
Starter code
#include <iostream>
int main() {
// Print the sizes of three types with sizeof
return 0;
}Sample solution
#include <iostream>
int main() {
// Print the sizes of three types with sizeof
std::cout << sizeof(int) << std::endl;
std::cout << sizeof(double) << std::endl;
std::cout << sizeof(char) << std::endl;
return 0;
}Expected output
4 8 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 sizeof syntax
std::cout << ____(int);
std::cout << sizeof(int);
Explanation: sizeof(int) gives the byte size of int.
2 Match types with sizes
| Term | Meaning |
|---|---|
sizeof(char) |
1 byte |
sizeof(int) |
4 bytes |
sizeof(double) |
8 bytes (double) |
sizeof(long long) |
8 bytes (long long) |
3 What is the typical value of sizeof(int) in bytes?
- 1
- 2
- 4 Correct answer
- 8
Explanation: int is typically 4 bytes.