Section 5.8. The sizeof Operator


5.8. The sizeof Operator

The sizeof operator returns a value of type size_t (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:

      sizeof (type name);      sizeof (expr);      sizeof expr; 

Applying sizeof to an expr returns the size of the result type of that expression:

      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) 

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 1

  • sizeof a reference type returns the size of the memory necessary to contain an object of the referenced type

  • sizeof 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 dereferenced

  • sizeof an array is equivalent to taking the sizeof the element type times the number of elements in the array

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; 




C++ Primer
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2006
Pages: 223
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net