< previous page page_987 next page >

Page 987
Reference Types
According to Figure 17-1, there is only one built-in type remaining: the reference type. Like pointer variables, reference variables contain the addresses of other variables. The statement
int& intRef;
declares that intRef is a variable that can contain the address of an int variable. Here is the syntax template for declaring reference variables:
0987-01.gif
Although reference variables and pointer variables both contain addresses of data objects, there are two fundamental differences. First, the dereferencing and address-of operators (* and &) are not used with reference variables. After a reference variable has been declared, the compiler invisibly dereferences every single appearance of that reference variable. This difference is illustrated below:
Using a reference variable
Using a pointer variable
int gamma = 26;
int  gamma = 26;
int& intRef = gamma;
int* intPtr = &gamma;
// Assert: intRef points
// Assert: intPtr points
//         to gamma
//         to gamma
intRef = 35;
*intPtr = 35;
// Assert: gamma == 35
// Assert: gamma == 35
intRef = intRef + 3
*intPtr = *intPtr + 3;
// Assert: gamma == 38
// Assert: gamma == 38

Some programmers like to think of a reference variable as an alias for another variable. In the preceding code, we can think of intRef as an alias for gamma. After intRef is initialized in its declaration, everything we do to intRef is actually happening to gamma.

 
< previous page page_987 next page >