5.8. The sizeof Operator
Section 3.5.2, p. 104) that is the size, in bytes (Section 2.1, p. 35), of an object or type name. The result of sizeof expression is a compile-time constant. The sizeof operator takes one of the following forms:
Applying sizeof to an expr returns the size of the result type of that expression:
sizeof (type name);
sizeof (expr);
sizeof expr;
Evaluating sizeof expr does not evaluate the expression. In particular, in sizeof *p, the pointer p may hold an invalid address, because p is not dereferenced.The result of applying sizeof depends in part on the type involved:sizeof char or an expression of type char is guaranteed to be 1sizeof a reference type returns the size of the memory necessary to contain an object of the referenced typesizeof a pointer returns the size needed hold a pointer; to obtain the size of the object to which the pointer points, the pointer must be dereferencedsizeof an array is equivalent to taking the sizeof the element type times the number of elements in the array
Sales_item item, *p;
// three ways to obtain size required to hold an object of type Sales_item
sizeof(Sales_item); // size required to hold an object of type Sales_item
sizeof item; // size of item's type, e.g., sizeof(Sales_item)
sizeof *p; // size of type to which p points, e.g., sizeof(Sales_item)
Because sizeof returns the size of the entire array, we can determine the number of elements by dividing the sizeof the array by the sizeof an element:
// sizeof(ia)/sizeof(*ia) returns the number of elements in ia
int sz = sizeof(ia)/sizeof(*ia);
Exercises Section 5.8
Exercise 5.22:Write a program to print the size of each of the built-in types.Exercise 5.23:Predict the output of the following program and explain your reasoning. Now run the program. Is the output what you expected? If not, figure out why.
int x[10]; int *p = x;
cout << sizeof(x)/sizeof(*x) << endl;
cout << sizeof(p)/sizeof(*p) << endl;