using namespace std;
void swap_numbers(int &num1, int &num2);
int &Ref = num;
Ref = 8;
cout << "num = " << num << endl << endl;
int num1 = 1;
int num2 = 2;
cout << "num1 = " << num1 << endl << "num2 = " << num2;
void swap_numbers(int &num1, int &num2)
int temp = num1;
num1 = num2;
num2 = temp;
This tutorial demonsterates the use of references.
The ability to use a reference is one of the things that separates c++
from the other programming languages. A Reference can be defined as an extra
name for an already existing variable. When you see this symbol & in c++ it
means that a reference is used.
When we declare a variable it's really just a series of memory cells,
that we can acess by an identifier.
example: a short int uses 16 bit (2 byte), a long int uses 32 bit (4 byte)
Let say that when you declare int myVariable; it uses 32 bit,
and the variable gets an unique address in memory.
A good simile for the computer memory can be a street in a city.
On a street all houses are consecutively numbered with an unique
identifier so if we talk about 27th of Sesame Street we will be
able to find that place without loss, since there must be only one
house with that number and, in addition, we know that that house
will be between houses 26 and 28.
In the same way in which houses in a street are numbered,
the operating system organizes the memory with unique and
consecutive numbers, so if we talk about location 1776 in the
memory, we know that there is only one location with that address
and also that is between addresses 1775 and 1777.
At the moment in which we declare a variable this one must be stored
in a concrete location/address in this succession of cells (the memory).
We generally do not decide where the variable is to be placed - fortunately
that is something automatically done by the compiler and the
operating system on runtime, but once the operating system has
assigned an address there are some cases in which we may be
interested in knowing where the variable is stored.
This can be done by preceding the variable identifier by an
ampersand sign (&), which literally means "address of".
When we use &num1 we refer to the address of num1.
So when we pass in the reference of the integer num1 and num2,
and use our swap function. We swap the actual numbers
of num1 and num2 evan thoug they are declared in an other function.
This is also called an out-argument. Functions can only return one value,
but they can have many out-arguments.
A referance can not be declared without a variable to refer to.