Consider a swap function which passes arguments by value.
#include <iostream.h>
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
int main()
{
int A, B;
cin >> A >> B;
cout << "A: " <<
A << "." << endl;
cout << "B: " <<
B << "." << endl;
swap(A, B);
cout << "A: " <<
A << "." << endl;
cout << "B: " <<
B << "." << endl;
return 0;
}
Input:
3 5
Output:
A: 3.
B: 5.
A: 3.
B: 5.
View the output. Is that what you would have expected based on the name of the function? Probably not. One would expect the swap function to actually swap the two pieces of data.
To understand this phenomenon, consider the actions which occur in memory:
We declare the variables A and B. Therefore in memory we have space to retain two pieces of information.
__
__
A ---> |__|
B ---> |__|
We take input from the keyboard.
___
___
A ---> |
| B ---> | |
| 3 |
| 5 |
|___|
|___|
When A and B are passed to the swap()
function copies are made for x and y.
___
___
A ---> |
| B ---> | |
| 3 |
| 5 |
|___|
|___|
___
___
x ---> |
| y ---> | |
| 3 |
| 5 |
|___|
|___|
We then perform the statements in the
body, swapping the copies.
___
___
A ---> |
| B ---> | |
| 3 |
| 5 |
|___|
|___|
___
___
x ---> |
| y ---> | |
| 5 |
| 3 |
|___|
|___|
Note that after the swap has occurred,
the original values of A and B are retained.
Consider the previous program with the swap() function implemented with pass by reference.
#include <iostream.h>
void swap(int &x, int &y) {
int temp = x;
x = y;
y = temp;
}
int main()
{
int A, B;
cin >> A >> B;
cout << "A: " <<
A << "." << endl;
cout << "B: " <<
B << "." << endl;
swap(A, B);
cout << "A: " <<
A << "." << endl;
cout << "B: " <<
B << "." << endl;
return 0;
}
Input:
3 5
Output:
A: 3.
B: 5.
A: 5.
B: 3.
With this example we see that the actual values are swapped within the function. Note how we indicate that we want to pass by reference: we do so with the ampersand (&) between the data type and the variable name.
We declare the variables A and B.
Therefore in memory we have space to retain two pieces of information just
as before.
__
__
A ---> |__|
B ---> |__|
We take input from the keyboard.
___
___
A ---> |
| B ---> | |
| 3 |
| 5 |
|___|
|___|
When A and B are passed to the swap()
function x and y point to the same space in memory.
x
y
|
|
|
|
v
v
___
___
A ---> |
| B ---> | |
| 3 |
| 5 |
|___|
|___|
We then perform the statements in the body, swapping the originals.
x
y
|
|
|
|
v
v
___
___
A ---> |
| B ---> | |
| 5 |
| 3 |
|___|
|___|
After we return from the function,
we are left with:
___
___
A ---> |
| B ---> | |
| 5 |
| 3 |
|___|
|___|
The result is that the values are swapped
appropriately.