Learn how the sizeof operator works in C++ with easy examples. Understand how to find the size of variables and data types in bytes for memory management and C++ programming.
sizeof Operator?The sizeof operator is used to find the size of a data type or variable in bytes.
sizeof(variable)
or
sizeof(data_type)
The result of sizeof is given in bytes.
sizeof with Data Types#include <iostream>
using namespace std;
int main() {
cout << sizeof(int) << endl;
cout << sizeof(float) << endl;
cout << sizeof(double) << endl;
cout << sizeof(char) << endl;
return 0;
}
Possible Output:
4
4
8
1
Note: The size of some data types can vary depending on the compiler and computer system.
charis always 1 byte.
sizeof with Variables#include <iostream>
using namespace std;
int main() {
int age = 20;
double salary = 50000.5;
char grade = 'A';
cout << sizeof(age) << endl;
cout << sizeof(salary) << endl;
cout << sizeof(grade) << endl;
return 0;
}
Possible Output:
4
8
1
sizeof(age) → finds the size of the int variable.sizeof(salary) → finds the size of the double variable.sizeof(grade) → finds the size of the char variable.sizeof Does Not Give the ValueConsider:
int age = 20;
cout << age << endl;
cout << sizeof(age) << endl;
Output:
20
4
Here:
age gives the value → 20sizeof(age) gives the memory size → 4 bytes on a typical system.sizeof with Arrayssizeof can also be used with arrays.
#include <iostream>
using namespace std;
int main() {
int numbers[5];
cout << sizeof(numbers);
return 0;
}
If an int is 4 bytes:
5 × 4 = 20 bytes
Output:
20
We can use sizeof to find the number of elements in an array:
int numbers[5];
int total = sizeof(numbers) / sizeof(numbers[0]);
cout << total;
Output:
5
sizeof(numbers) = 20 bytes
sizeof(numbers[0]) = 4 bytes
20 / 4 = 5
Therefore, the array contains 5 elements.
| Expression | Purpose |
|---|---|
sizeof(int) |
Size of int |
sizeof(float) |
Size of float |
sizeof(x) |
Size of variable x |
sizeof(array) |
Total size of array |
sizeof(array) / sizeof(array[0]) |
Number of array elements |
sizeoftells us how many bytes are occupied by a data type, variable, or object.
Important: sizeof returns a size in bytes, not bits.