Sams Teach Yourself C++ in 21 Days

(singke) #1
Exploiting References 265

9


23:
24: temp = *px;
25: *px = *py;
26: *py = temp;
27:
28: cout << “Swap. After swap, *px: “ << *px <<
29: “ *py: “ << *py << endl;
30:
31: }

Main. Before swap, x: 5 y: 10
Swap. Before swap, *px: 5 *py: 10
Swap. After swap, *px: 10 *py: 5
Main. After swap, x: 10 y: 5
Success! On line 5, the prototype of swap()is changed to indicate that its two
parameters will be pointers to intrather than intvariables. When swap()is
called on line 12, the addresses of xand yare passed as the arguments. You can see that
the addresses are passed because the address-of operator (&) is being used.
On line 19, a local variable,temp, is declared in the swap()function. tempneed not be a
pointer; it will just hold the value of *px(that is, the value of xin the calling function)
for the life of the function. After the function returns,tempis no longer needed.
On line 24,tempis assigned the value at px. On line 25, the value at pxis assigned to the
value at py. On line 26, the value stashed in temp(that is, the original value at px) is put
into py.
The net effect of this is that the values in the calling function, whose address was passed
to swap(), are, in fact, swapped.

Implementing swap()with References ..........................................................


The preceding program works, but the syntax of the swap()function is cumbersome in
two ways. First, the repeated need to dereference the pointers within the swap()function
makes it error-prone—for instance, if you fail to dereference the pointer, the compiler
still lets you assign an integer to the pointer, and a subsequent user experiences an
addressing error. This is also hard to read. Finally, the need to pass the address of the
variables in the calling function makes the inner workings of swap()overly apparent to
its users.
It is a goal of an object-oriented language such as C++ to prevent the user of a function
from worrying about how it works. Passing by pointers puts the burden on the calling

OUTPUT


LISTING9.6 continued


ANALYSIS
Free download pdf