< previous page page_135 next page >

Page 135
LISTING 9.1 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 5:
 6:   int main()
 7:   {
 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 <<  &shortVar << \n;
14:      cout << longVar:\t  << longVar;
15:      cout << \tAddress of longVar:\t  <<  &longVar  << \n;
16:      cout << sVar:\t\t << sVar  << \tAddress of sVar:\t <<
17: &sVar << \n;
18:
19:      return 0;
20:   }   }

Output:
shortVar: 5      Address of shortVar: 0x8fc9:fff4
longVar:  65535   Address of longVar:  0x8fc9:fff2
sVar:     -65535   Address of sVar:     0x8fc9:ffee
(Your printout may look different.)
Analysis: Three variables are declared and initialized: a short in line 7, an unsigned long in line 8, and a long in line 9. Their values and addresses are printed in lines 1115, by using the address of operator (&).
The value of shortVar is 5 (as expected), and its address is 0x8fc9:fff4 when run on my 80386-based computer. This complicated address is computer specific and can change slightly each time the program is run. Your results will be different. What doesn't change, however, is that the difference in the first two addresses is 2 bytes if your computer uses 2-byte short integers. The difference between the second and third is 4 bytes if your computer uses 4-byte long integers. Figure 9.2 illustrates how the variables in this program would be stored in memory. (Note that on some computers the difference will be 4 bytes on both, depending on how your compiler is configured.)
There is no reason why you would need to know the actual numeric value of the address of each variable. What you care about is that each one has an address and that the right amount of memory is set aside.
How does the compiler know how much memory each variable needs? You tell the compiler how much memory to allow for your variables by declaring the variable type.
Therefore, if you declare your variable to be of type unsigned long, the compiler knows to set aside 4 bytes of memory because every unsigned long takes 4 bytes. The compiler takes care of assigning the actual address.

 
< previous page page_135 next page >

If you like this book, buy it!