sizeof – an operator by itself
The sizeof
operator stands alone because it satisfies an unusual need. sizeof gives
you information about the amount of memory allocated for data items. As
described earlier in this chapter, sizeof tells you the number of bytes
used by any particular variable. It can also give the size of a data type (with
no variable name):
//: C03:sizeof.cpp
#include <iostream>
using namespace std;
int main() {
cout << "sizeof(double) = " << sizeof(double);
cout << ", sizeof(char) = " << sizeof(char);
} ///:~
By definition, the
sizeof any type of
char (signed, unsigned or plain) is always one, regardless
of whether the underlying storage for a char is actually one byte. For
all other types, the result is the size in bytes.
Note that sizeof is an operator,
not a function. If you apply it to a type, it must be used with the
parenthesized form shown above, but if you apply it to a variable you can use it
without parentheses:
//: C03:sizeofOperator.cpp
int main() {
int x;
int i = sizeof x;
} ///:~
sizeof can also give you the sizes
of user-defined data types. This is used later in the
book.