Jump to content

Programming Fundamentals/Address Operator

From Wikibooks, open books for an open world

An introduction to the address operator as used within the C++ programming language.

Address Operator in C++

[edit | edit source]

"Every variable is assigned a memory location whose address can be retrieved using the address operator &. The address of a memory location is called a pointer. Every variable in an executing program is allocated a section of memory large enough to hold a value of that variable’s type."[1] Thus, whether the variables are global scope and use the data area for storage or local scope and use the stack for storage; you can ask the question at what address in the memory does this variable exist. Given an integer variable named age:

int age = 47;

We can use the address operator [which is the ampersand or &] to determine where it exists (or its address) in the memory by:

&age

This expression is a pointer data type. The concept of an address and a pointer are one in the same. A pointer points to the location in memory because the value of a pointer is the address were the data item resides in the memory.

The address operator is commonly used in two ways:

  1. To do parameter passing by reference
  2. To establish the value of pointers

Both of these items are covered in the supplemental links to this module.

You can print out the value of the address with the following code:

cout << &age;

This will by default print the value in hexadecimal. Some people prefer an integer value and to print it as an integer you will need to cast the address into a long data type:

cout << long(&age);

One additional tidbit, an array’s name is by definition a pointer to the arrays first element. Thus:

int iqs[] = {122, 105, 131, 97};

establishes "iqs" as a pointer to the array.

Definitions

[edit | edit source]
address operator
The ampersand or &.
pointer
A variable that holds an address as its value.

References

[edit | edit source]
  1. Tony Gaddis, Judy Walters and Godfrey Muganda, Starting Out with C++ Early Objects Sixth Edition (United States of America: Pearson – Addison Wesley, 2008) 597.