|
|
|
|
|
|
|
The second difference between reference and pointer variables is that the compiler treats a reference variable as if it were a constant pointer. It cannot be reassigned after being initialized. In fact, absolutely no operations apply directly to a reference variable except initialization. (In this context, C++ defines initialization to mean (a) explicit initialization in a declaration, (b) implicit initialization by passing an actual parameter to a formal parameter, or (c) implicit initialization by returning a function value.) For example, the statement |
|
|
|
|
|
|
|
|
does not increment intRef; it increments the variable to which intRef points. Why? Because the compiler implicitly dereferences each appearance of the name intRef. |
|
|
|
|
|
|
|
|
The principal advantage of reference variables, then, is notational convenience. Unlike pointer variables, reference variables do not require the programmer to continually prefix the variable with an asterisk in order to access the pointed-to variable. |
|
|
|
 |
|
 |
|
|
Reference Type A simple data type consisting of an unbounded set of values, each of which is the address of a variable of a given type. The only operation defined on a reference variable is initialization, after which every appearance of the variable is implicitly dereferenced. |
|
|
|
|
|
|
|
|
A common use of reference variables is to pass nonarray parameters by reference instead of by value (as we have been doing ever since Chapter 7). Suppose the programmer wants to exchange the contents of two float variables with the function call |
|
|
|
|
|
|
|
|
Because C++ normally passes simple variables by value, the following code fails: |
|
|
|
|
|
|
|
|
void Swap( float x, float y )
// Caution: This routine does not work
{
float temp = x;
x = y;
|
|
|
|
|
|