The sizeof operator

The sizeof operator yields the size in bytes of the operand, which can be an expression or the parenthesized name of a type.

Read syntax diagramSkip visual syntax diagramsizeof operator syntax
 
>>-sizeof--+-expr------------+---------------------------------><
           '-(--type-name--)-'
 

The result for either kind of operand is not an lvalue, but a constant integer value. The type of the result is the unsigned integral type size_t defined in the header file stddef.h.

Except in preprocessor directives, you can use a sizeof expression wherever an integral constant is required. One of the most common uses for the sizeof operator is to determine the size of objects that are referred to during storage allocation, input, and output functions.

Another use of sizeof is in porting code across platforms. You can use the sizeof operator to determine the size that a data type represents. For example:

sizeof(int);

The sizeof operator applied to a type name yields the amount of memory that would be used by an object of that type, including any internal or trailing padding.

For compound types, results are as follows:

Operand Result
An array The result is the total number of bytes in the array. For example, in an array with 10 elements, the size is equal to 10 times the size of a single element. The compiler does not convert the array to a pointer before evaluating the expression.
C++ A class The result is always nonzero, and is equal to the number of bytes in an object of that class including any padding required for placing class objects in an array.
C++ A reference The result is the size of the referenced object.

The sizeof operator may not be applied to:

The sizeof operator applied to an expression yields the same result as if it had been applied to only the name of the type of the expression. At compile time, the compiler analyzes the expression to determine its type. None of the usual type conversions that occur in the type analysis of the expression are directly attributable to the sizeof operator. However, if the operand contains operators that perform conversions, the compiler does take these conversions into consideration in determining the type. For example, the second line of the following sample causes the usual arithmetic conversions to be performed. Assuming that a short uses 2 bytes of storage and an int uses 4 bytes,

short x; ... sizeof (x)         /* the value of sizeof operator is 2 */
short x; ... sizeof (x + 1)     /* value is 4, result of addition is type int */

The result of the expression x + 1 has type int and is equivalent to sizeof(int). The value is also 4 if x has type char, short, or int or any enumeration type.

Related information



[ Top of Page | Previous Page | Next Page | Contents | Index ]