Address-of operator (&) vs reference operator(&)

In C++ there’re two different syntax units:

&variable; // extracts address of variable

and

Type& ref = variable; // creates reference called ref to variable

Easy usage example:

int v = 5;

cout << v << endl; // prints 5
cout << &v << endl; // prints address of v

int* p;
p = &v; // stores address of v into p (p is a pointer to int)

int& r = v;

cout << r << endl; // prints 5

r = 6;

cout << r << endl; // prints 6
cout << v << endl; // prints 6 too because r is a reference to v

As for using references in functions, you should google “passing by reference in C++”, there’re many tutorials about it.

Leave a Comment