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:
Pass By Value
A copy of the argument’s value is passed to the function
The called function cannot alter the original value in the calling function
Should be used if called function does not need to modify the value of the calling function’s variable
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
The called function is allowed to alter the original value of the calling function’s variable
Accomplished by using pointer variables and passing the address of the variable
Should only be used with trusted called functions
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
The called function is allowed to alter the original value of the calling function’s variable
Accomplished by using reference variables
Each reference parameter is an alias for its corresponding argument
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)