The sizeof operator yields the size of its operand with respect to the size of type char. The result of the sizeof operator is of type size_t, an integral type defined in the include file STDDEF.H. The operand to sizeof can be one of the following:
When the sizeof operator is applied to an object of type char, it yields 1. When the sizeof operator is applied to an array, it yields the total number of bytes in that array. For example:
#include <iostream.h>
void main()
{
char szHello[] = "Hello, world!";
cout << "The size of the type of " << szHello << " is: "
<< sizeof( char ) << "\n";
cout << "The length of " << szHello << " is: "
<< sizeof szHello << "\n";
}
The program output is:
The size of the type of Hello, world! is: 1
The length of Hello, world! is: 14
When the sizeof operator is applied to a class, struct, or union type, the result is the number of bytes in an object of that class, struct, or union type, plus any padding added to align members on word boundaries. (The /Zp [pack structure members] compiler option and the pack pragma affect alignment boundaries for members.) The sizeof operator never yields 0, even for an empty class.
The sizeof operator cannot be used with the following operands:
When the sizeof operator is applied to a reference, the result is the same as if sizeof had been applied to the object itself.
The sizeof operator is often used to calculate the number of elements in an array using an expression of the form:
sizeof array / sizeof array[0]