< previous page page_171 next page >

Page 171
LISTING 11.6 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
25:             rx = ry;
26:             ry = temp;
27:             cout << Swap. After swap, rx: ;
28:             cout << rx <<  ry:  << ry << \n;
29:
30:        }

Output:
Main. Before swap, x:5 y: 10
Swap. Before swap, rx:5 ry:10
Swap. After swap, rx:10 ry:5
Main. After swap, x:10, y:5
Analysis: Just as in the example with pointers, two variables are declared on line 10, and their values are printed on line 12. On line 13 the function swap() is called, but note that x and y are passed, not their addresses. The calling function simply passes the variables.
When swap() is called, program execution jumps to line 18, where the variables are identified as references. Their values are printed on lines 21 and 22, but note that no special operators are required. These are aliases for the original values, and can be used as such.
On lines 2426 the values are swapped, and then they're printed on lines 27 and 28. Program execution jumps back to the calling function, and on line 14 the values are printed in main(). Because the parameters to swap() are declared to be references, the values from main() are passed by reference, and thus are changed in main() as well.
References provide the convenience and ease of use of normal variables, with the power and pass-by-reference capability of pointers!
Understanding Function Headers and Prototypes.
Listing 11.7 shows swap() using pointers, and Listing 11.8 shows it using references. Using the function that takes references is easier, and the code is easier to read; but how does the calling function know if the values are passed by reference or by value? As a client (or user) of swap(), the programmer must ensure that swap() will in fact change the parameters.
This is another use for the function prototype. By examining the parameters declared in the prototype, which is typically in a header file along with all the other prototypes, the programmer knows that the values passed into swap() are passed by reference, and thus will be swapped properly.

 
< previous page page_171 next page >

If you like this book, buy it!