4.9. The sizeof Operator
The sizeof operator returns the size, in bytes, of an expression or a type name. The operator is right associative. The result of sizeof is a constant expression (§ 2.4.4, p. 65) of type size_t (§ 3.5.2, p. 116). The operator takes one of two forms:
sizeof (type)
sizeof exprIn the second form, sizeof returns the size of the type returned by the given expression. The sizeof operator is unusual in that it does not evaluate its operand:
Sales_data data, *p;
sizeof(Sales_data); // size required to hold an object of type Sales_data
sizeof data; // size of data's type, i.e., sizeof(Sales_data)
sizeof p; // size of a pointer
sizeof *p; // size of the type to which p points, i.e., sizeof(Sales_data)
sizeof data.revenue; // size of the type of Sales_data's revenue member
sizeof Sales_data::revenue; // alternative way to get the size of revenueThe most interesting of these examples is sizeof *p. First, because sizeof is right associative and has the same precedence as *, this expression groups right to left. That is, it is equivalent to sizeof (*p). Second, because sizeof does not evaluate its operand, it doesn’t matter that p is an invalid (i.e., uninitialized) pointer (§ 2.3.2, p. 52). Dereferencing an invalid pointer as the operand to sizeof is safe because the pointer is not actually used. sizeof doesn’t need dereference the pointer to know what type it will return.
Under the new standard, we can use the scope operator to ask for the size of a member of a class type. Ordinarily we can only access the members of a class through an object of that type. We don’t need to supply an object, because sizeof does not need to fetch the member to know its size.
The result of applying sizeof depends in part on the type involved:
sizeof charor an expression of typecharis guaranteed to be 1.sizeofa reference type returns the size of an object of the referenced type.sizeofa pointer returns the size needed hold a pointer.sizeofa dereferenced pointer returns the size of an object of the type to which the pointer points; the pointer need not be valid.sizeofan array is the size of the entire array. It is equivalent to taking thesizeofthe element type times the number of elements in the array. Note thatsizeofdoes not convert the array to a pointer.sizeofastringor avectorreturns only the size of the fixed part of these types; it does not return the size used by the object’s elements.
Because sizeof returns the size of the entire array, we can determine the number of elements in an array by dividing the array size by the element size:
// sizeof(ia)/sizeof(*ia) returns the number of elements in ia
constexpr size_t sz = sizeof(ia)/sizeof(*ia);
int arr2[sz]; // ok sizeof returns a constant expression § 2.4.4 (p. 65)Because sizeof returns a constant expression, we can use the result of a sizeof expression to specify the dimension of an array.