Exploiting References 267
9
Just as in the example with pointers, two variables are declared on line 10, and
their values are printed on line 12. On line 15, the function swap()is called, but
note that xand y, not their addresses, are passed. The calling function simply passes the
variables.
When swap()is called, program execution jumps to line 23, where the variables are
identified as references. The values from the variables are printed on line 27, but note
that no special operators are required. These variables are aliases for the original vari-
ables and can be used as such.
On lines 30–32, the values are swapped, and then they’re printed on line 35. Program
execution jumps back to the calling function, and on line 17, the values are printed in
main(). Because the parameters to swap()are declared to be references, the variables
from main()are passed by reference, and thus their changed values are what is seen in
main()as well.
As you can see from this listing, 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 9.6 shows swap()using pointers, and Listing 9.7 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. On line 6 of Listing 9.7, you can see the prototype for
swap()—you can see that the two parameters are passed as references.
If swap()had been a member function of a class, the class declaration, also available in a
header file, would have supplied this information.
In C++, clients of classes and functions can rely on the header file to tell all that is
needed; it acts as the interface to the class or function. The actual implementation is hid-
den from the client. This enables the programmer to focus on the problem at hand and to
use the class or function without concern for how it works.
ANALYSIS