13 Type Size

Each data type has a size, which is the number of bytes (see Storage and Data) that it occupies in memory. To refer to the size in a C program, use sizeof. There are two ways to use it:

sizeof expression

This gives the size of expression, based on its data type. It does not calculate the value of expression, only its size, so if expression includes side effects or function calls, they do not happen. Therefore, sizeof with an expression as argument is always a compile-time operation that has zero run-time cost, unless it applies to a variable-size array.

A value that is a bit field (see Bit Fields) is not allowed as an operand of sizeof.

For example,

double a;

i = sizeof a + 10;

sets i to 18 on most computers because a occupies 8 bytes.

Here’s how to determine the number of elements in an array arr:

(sizeof arr / sizeof arr[0])

The expression sizeof arr gives the size of the array, not the size of a pointer to an element. However, if expression is a function parameter that was declared as an array, that variable really has a pointer type (see Array parameters are pointers), so the result is the size of that pointer.

sizeof (type)

This gives the size of type. For example,

i = sizeof (double) + 10;

is equivalent to the previous example.

Warning: If type contains expressions which have side effects, those expressions are actually computed and any side effects in them do occur.

You can’t apply sizeof to an incomplete type (see Incomplete Types). Using it on a function type or void gives 1 in GNU C, which makes adding an integer to these pointer types work as desired (see Pointer Arithmetic).

Warning: When you use sizeof with a type instead of an expression, you must write parentheses around the type.

Warning: When applying sizeof to the result of a cast (see Explicit Type Conversion), you must write parentheses around the cast expression to avoid an ambiguity in the grammar of C. Specifically,

sizeof (int) -x

parses as

(sizeof (int)) - x

If what you want is

sizeof ((int) -x)

you must write it that way, with parentheses.

The data type of the value of the sizeof operator is always an unsigned integer type; which one of those types depends on the machine. The header file stddef.h defines size_t as a name for such a type. See Defining Typedef Names.