An alias for a variable
Utilises the ampersand & symbol
Syntax: int & myAlias = myVar ; //now myAlias and myVar are effectively the same
Any changes to the reference are reflected in the original, and vice-versa.
References are similar to pointers, but do not work under the principles of 'address of' or dereferencing.
- alias for a variable
- when declaring must be initialised to a variable
- cannot have NULL references
- data type (primitive or abstract) must precede the ampersand &
- dataType & alias
This example assigns two references and also shows references being passed into a function:
#include <iostream> using namespace std; void swap(int &x, int &y){ x = x + y ; y = x - y ; x = x - y ; return ; } int main () { int a = 17 ; int b = 42 ; int & i = a ; //defining i as a reference to a int & j = b ; //defining j as a reference to b //now using i and j as aliases to a and b cout << "a before swap: " << i << endl; cout << "b before swap: " << j << endl; //calling the swap function using the aliases swap(i, j) ; //displaying the swap result using the original variables cout << "a after swap: " << a << endl; cout << "b after swap: " << b << endl; return 0; }
Compile & Run:
a before swap: 17 b before swap: 42 a after swap: 42 b after swap: 17 |
*Note: Maybe slightly confusing with respect to the ampersand & symbol also being used as the 'address of' operator. The thing to remember with references is that they should always be initialised to an existing variable.