Programming Fundamentals/Sizeof Operator

From Wikibooks, open books for an open world
Jump to navigation Jump to search

An explanation of the sizeof operator with examples as used within the C++ programming language.

Overview[edit | edit source]

Every data item, constants and variables, not only have a data type, but the data type determines how many bytes the item will use in the memory of the computer. The size of each data type varies with the complier being used and the computer. This effect is known as being machine dependent. Additionally, there have been some size changes with upgrades to the language. In "C" the int data type was allocated 2 bytes of memory storage on an Intel compatible central processing unit (cpu) machine. In "C++" an int is allocated 4 bytes.

There is an operator named "sizeof (… )" that is a unary operator, that is it has only one operand. The operand is to the right of the operator and is placed within the parentheses if it is a data type. The operand may be any data type (including those created by typedef). If the operand is an identifier name it does not need to go inside a set of parentheses. It works for both variable and memory constant identifier names. This operator is unique in that it performs its calculation at compile time for global scoped items and at run time for local scoped items. Examples:

cout << "The size of an integer is: " << sizeof (int);

The compiler would determine the byte size of an integer on the specific machine and in essence replaces the sizeof operator with a value. Integers are usually 4 bytes long, thus the line of code would be changed to:

cout << "The size of an integer is: " << 4;

If you place an identifier name that represents a data storage area (variable or memory constant), it looks at the definition for the identifier name. NOTE: the parentheses are not needed and often not included for an identifier name.

Example 1: sizeof with a Variable[edit | edit source]

double money;     // variable set up with initialization
    then later on in the program
cout << "The size of money is: " << sizeof money;

The compiler would determine the byte size of money by looking at the definition where it indicates that the data type is double. The double data type on the specific machine (usually 8 bytes) would replace the code and it would become:

cout << "The size of money is: " << 8;

Definitions[edit | edit source]

sizeof
An operator that tells you how many bytes a data type occupies in storage.