sizeof() Operator

Although this operator, 'sizeof()', looks like a function it is not one. First of all because it is evaluated at compile time and has a constant value, and second of all because it operates on types or identifiers (but not the value associated with the identifier). In the first case, its value is the size in bytes of the given type for that implementation. A different value may be given on a different computer and perhaps also on the same computer but with a different compiler. In the second case, it is the size in bytes of the memory space reserved for that variable named by the identifier.

In all cases, the value of the sizeof operator applied to its argument, is a constant known at compile time. This constant replaces the expression.

The fact that when the sizeof operator applied to a type, whether a simple type or compound type, is implementation dependent, is one of the more important uses of this operator. It lets you know what size a given type is on the computer for the compiler you are using.

Since it is possible to let an initialization determine the size of a data object, this operator lets you find out what size (in bytes) that data object is.

The following initialization has the size of the array determined by the number of items in the initialization list:

	long int how_big_am_i[] = { 234L, 678948L, -65464L };

To find out how many entries are in the array one writes:

	sizeof(how_big_am_i)/sizeof(long int)

Since sizeof() always gives an answer in bytes, it is necessary to scale that value by the size of the type, long int in this case, as was done by dividing by that value. Of course in this case it is easy to count the number of items and manually create:

	#define SIZE_HOW_BIG_AM_I 3

but this has two disadvantages. First, and most important, one must know and remember to change the manifest constant if the number of entries in the array changes. Second, the list may not be so short and the counting process can be in error leading to indexing the array out of bounds or not using all of the values. It is always better to let the computer (and compiler) do as much as it can for you.


© 1991-2008 Prem Sobel. All Rights Reserved.