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 Visual C++ 2012 on a Windows 7 computer. Type sizes are platform dependent. On another system, for example, double
and long double
may be of different sizes.
1 // Fig. 8.14: fig08_14.cpp
2 // sizeof operator used to determine standard data type sizes.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 char c; // variable of type char
9 short s; // variable of type short
10 int i; // variable of type int
11 long l; // variable of type long
12 long ll; // variable of type long long
13 float f; // variable of type float
14 double d; // variable of type double
15 long double ld; // variable of type long double
16 int array[ 20 ]; // built-in array of int
17 int *ptr = array; // variable of type int *
18
19 cout << "sizeof c = " << sizeof c
20 << " sizeof(char) = " << sizeof( char )
21 << "
sizeof s = " << sizeof s
22 << " sizeof(short) = " << sizeof( short )
23 << "
sizeof i = " << sizeof i
24 << " sizeof(int) = " << sizeof( int )
25 << "
sizeof l = " << sizeof l
26 << " sizeof(long) = " << sizeof( long )
27 << "
sizeof ll = " << sizeof ll
28 << " sizeof(long long) = " << sizeof( long long )
29 << "
sizeof f = " << sizeof f
30 << " sizeof(float) = " << sizeof( float )
31 << "
sizeof d = " << sizeof d
32 << " sizeof(double) = " << sizeof( double )
33 << "
sizeof ld = " << sizeof ld
34 << " sizeof(long double) = " << sizeof( long double )
35 << "
sizeof array = " << sizeof array
36 << "
sizeof ptr = " << sizeof ptr << endl;
37 } // end main
sizeof c = 1 sizeof(char) = 1
sizeof s = 2 sizeof(short) = 2
sizeof i = 4 sizeof(int) = 4
sizeof l = 4 sizeof(long) = 4
sizeof ll = 8 sizeof(long long) = 8
sizeof f = 4 sizeof(float) = 4
sizeof d = 8 sizeof(double) = 8
sizeof ld = 8 sizeof(long double) = 8
sizeof array = 80
sizeof ptr = 4
Portability Tip 8.1
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 use sizeof to 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 sizeof
’s operand is not evaluated.