1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

int i;
const intj = 1; const int& r = i; const int& s = j;

i = 2; j = 2; r = 2; s = 2;

// okay
// error
// error
// error

const reference variables and arguments to functions

Rather than have a large object pushed onto the stack, you can pass a reference to the object. If you want to indicate that the function won't be making any changes to the object, you can pass it by const reference. This is probably the most common use of references, since it acts like an "efficient call by value:''

void print_large_array( const int& ar[], int n )
or
void print_large_array( const int* &ar, int n )
The above two are equivalent.

const references to class data

A class acts like a struct that is passed implicitly to all its member functions. You can indicate that a member function does not modify the data area of its class by using const, giving the same "efficient call by value'' for the implicit class argument that the previous section gave to explicit arguments:

22-Mar-98

Page 11

C201/TAM