Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Pointers 223

8


LISTING8.1 Demonstrating the Address-of Operator


1: // Listing 8.1 Demonstrates address-of operator
2: // and addresses of local variables
3: #include <iostream>
4:
5: int main()
6: {
7: using namespace std;
8: unsigned short shortVar=5;
9: unsigned long longVar=65535;
10: long sVar = -65535;
11:
12: cout << “shortVar:\t” << shortVar;
13: cout << “\tAddress of shortVar:\t”;
14: cout << &shortVar << endl;
15:
16: cout << “longVar:\t” << longVar;
17: cout << “\tAddress of longVar:\t” ;
18: cout << &longVar << endl;
19:
20: cout << “sVar:\t\t” << sVar;
21: cout << “\tAddress of sVar:\t” ;
22: cout << &sVar << endl;
23:
24: return 0;
25: }

shortVar: 5 Address of shortVar: 0012FF7C
longVar: 65535 Address of longVar: 0012FF78
sVar: -65535 Address of sVar: 0012FF74
(Your printout might look different, especially the last column.)
Three variables are declared and initialized: an unsigned shorton line 8, an
unsigned longon line 9, and a longon line 10. Their values and addresses are
printed on lines 12–22. You can see on lines 14, 18, and 22 that the address-of operator
(&) is used to get the address of the variable. This operator is simply placed on the front
of the variable name in order to have the address returned.
Line 12 prints the value of shortVaras 5 , which is expected. In the first line of the out-
put, you can see that its address is 0012FF7C when run on a Pentium (32-bit) computer.
This address is computer-specific and might change slightly each time the program is
run. Your results will be different.
When you declare a variable, the compiler determines how much memory to allow based
on the variable type. The compiler takes care of allocating memory and automatically

OUTPUT


ANALYSIS
Free download pdf