C++ sizeof Operator Explained: Usage & Examples
In C++, sizeof is an operator used to fetch the size of a type or variable in bytes. The syntax for it is as follows:
size of the type
size of the expression
type is a data type, while expression can be either an expression or a variable.
The sizeof operator returns the type size_t, which is an unsigned integer type.
The sizeof operator can be used in two ways:
- The sizeof(type) operator is used to get the size of a type, for example sizeof(int) will return the size of the int type, and sizeof(double) will return the size of the double type.
- sizeof(expression) is used to obtain the size of an expression or a variable. For example, sizeof(arr) will return the size of the array arr, while sizeof(x) will return the size of the variable x.
It is important to note that the sizeof operator does not actually calculate the value of the expression, but instead determines the size of the expression or variable at compile time. Therefore, the arr in sizeof(arr) is not modified or called.
For array types, sizeof returns the size of the entire array, not just the size of a pointer to the first element.
For example, the following examples demonstrate the usage of the sizeof operator:
#include <iostream>
int main() {
int x = 5;
int arr[10];
std::cout << "Size of int: " << sizeof(int) << " bytes" << std::endl;
std::cout << "Size of double: " << sizeof(double) << " bytes" << std::endl;
std::cout << "Size of x: " << sizeof(x) << " bytes" << std::endl;
std::cout << "Size of arr: " << sizeof(arr) << " bytes" << std::endl;
return 0;
}
Output result:
Size of int: 4 bytes
Size of double: 8 bytes
Size of x: 4 bytes
Size of arr: 40 bytes
In this example, sizeof(int) returns 4 because the int data type typically occupies 4 bytes. Additionally, sizeof(x) returns 4 because the variable x is of type int. Finally, sizeof(arr) returns 40 because the array arr contains 10 elements of type int, with each element occupying 4 bytes, totaling 40 bytes.