The unary operator sizeof is used to calculate the sizes of datatypes in Bytes in modern luanguages in the programming languages C and C++. It is an useful operation in memory allocation. In order to use it right, some tips that you may want to know:
- sizeof() is a compile-time function (macro-like function), not a run-time function. Therefore, you can declare array as: int arr[sizeof(int)];
- because sizeof() is a compile-time function, the equation in sizeof() function will not be calculated. For example: int i=3; int a = sizeof(i++); the value of i will not be changed after sizeof(i++);
- because sizeof() is a compile-time function, it can not help you determine the size of an array parameter. The following code will print out size 12 and 4.
void test_sizeof(int arr[]) { cout << "sizeof(arr) = " << sizeof(arr) << endl; } int main() { int arr[3]; cout << "sizeof(arr) =" << sizeof(arr) << endl; testsizeof(arr); }
- sizeof() can not be applied to incomplete datatype. Compile errors will be report when the following code is compiled:
class InCompClass; int main() { cout << "Sizeof(InComplete Types)" << sizeof(InComClass) << endl; }
- However, sizeof() can be used to determine the size of empty class type and 1 will be returned.
- When sizeof() is used to calculate the size of user-defined data structure, the size may not be equal to the sum of the size of data members because of the memory alignment in most compilers.
Comments