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

Overview

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.

Sizeof with a variable

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

Got questions? Get instant answers now!

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

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

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Programming fundamentals - a modular structured approach using c++. OpenStax CNX. Jan 10, 2013 Download for free at http://cnx.org/content/col10621/1.22
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Programming fundamentals - a modular structured approach using c++' conversation and receive update notifications?

Ask