Reference Variables

A reference variable is similar to a pointer in the sense that it provides another way to refer to a named area of storage. But unlike a pointer, a user does not have to physically dereference a reference, it is automatically done for you.

They are typically used as arguments to and returned values from functions, but it is possible to create a local reference variable within a routine.

The symbol that is used to create a reference variable is the ampersand (&)

Declaration format:   data_type &var_name = var_name2;

int y;
int &yref = y;

The important thing to notice here is that a reference variable MUST be assigned to a specific variable when it is created.

Once assigned, it will ALWAYS refer to that specific variable.

References and functions

As with pointers, when a reference is used as a function argument, any change that is made to the reference within the function, WILL be applied to the argument outside of the function.

We know have three ways to pass arguments to functions:

  1. Pass By Value
  2. Simulated Pass By Reference
  3. Pass By Reference

Pass By Value

Function Prototype:    return_value func_name(arg_data_type,...);
Function Header:       return_value func_name(arg_data_type arg_name,…)
Function Call:         func_name(calling_func_argument)

Simulated Pass By Reference

Function Prototype:    return_value func_name(arg_data_type *,...);
Function Header:       return_value func_name(arg_data_type *arg_name)
Function Call:         func_name(&calling_func_argument)

Pass By Reference

Function Prototype:    return_value func_name(arg_data_type &);                              
Function Header:       return_value func_name(arg_data_type &arg_name)                              
Function Call:         func_name(calling_func_argument)