The compile time unary operator sizeof determines the size in bytes of a built-in array or of any other data type, variable or constant during program compilation. When applied to a built-in array’s name, as in Fig. 8.13 (line 12), sizeof returns the total number of bytes in the built-in array as a value of type size_t. The computer we used to compile this program stores variables of type double in 8 bytes of memory, and numbers is declared to have 20 elements (line 10), so it uses 160 bytes in memory. When applied to a pointer parameter (line 20) in a function that receives a built-in array as an argument, the sizeof operator returns the size of the pointer in bytes (4 on the system we used)—not the built-in array’s size.
Common Programming Error 8.3
Using thesizeofoperator in a function to find the size in bytes of a built-in array parameter results in the size in bytes of a pointer, not the size in bytes of the built-in array.
The number of elements in a built-in array can be determined using the results of two sizeof operations. For example, to determine the number of elements in the built-in array numbers, use the following expression (which is evaluated at compile time):
sizeof numbers / sizeof(numbers[0])
The expression divides the number of bytes in numbers (160, assuming 8-byte doubles) by the number of bytes in the built-in array’s zeroth element (8)—resulting in the number of elements in numbers (20).
Determining the Sizes of the Fundamental Types, a Built-In Array and a Pointer
Figure 8.14 uses sizeof to calculate the number of bytes used to store many of the standard data types. The output was produced using the default settings in Xcode 7.2 on Mac OS X. Type sizes are platform dependent. When we run this program on Windows, for example, long is 4 bytes and and longlong is 8 bytes, whereas on our Mac, they’re both 8 bytes.
Portability Tip 8.2
The number of bytes used to store a particular data type may vary among systems. When writing programs that depend on data type sizes, always usesizeofto determine the number of bytes used to store the data types.
Operator sizeof can be applied to any expression or type name. When sizeof is applied to a variable name (which is not a built-in array’s name) or other expression, the number of bytes used to store the specific type of the expression is returned. The parentheses used with sizeof are required only if a type name (e.g., int) is supplied as its operand. The parentheses used with sizeof are not required when sizeof’s operand is an expression. Remember that sizeof is a compile-time operator, so its operand is not evaluated at runtime.