Task
Write a procedure that swaps the values of two variables.
The peculiarities of this task are that we need the changes made in the procedure to become known to the calling program.
Let's try to write the procedure like this:
void Swap ( int a, int b ) // with such a description of the procedure parameters,
{ // the values of the arguments (x and y) will be copied,
int c; // variables a and b are independent variables not related to x and y
c = a; a = b; b=c;
}
main()
{
int x=1, y=2;
Swap(x, y); // values of variables x and y (arguments) are copied into parameters a and b
cout << "x=" << x<< ", y=" << y; // x=1, y=2
}
If you run this program, you can see that the values of the variables x
and y
have not changed. In order for the parameters to change the values of the arguments, you must use passing data by reference. To do this, after the name of the data type in the header of the subroutine, you must put the sign & code> ("ampersand").
void Swap ( int & a, int & b ) // now variables a and b get addresses of variables x and y in memory
{
int c;
c = a; a = b; b=c;
}
Usage: If you pass an argument by reference, then only the variable name (NOT a number and NOT an arithmetic expression) can be in this place when calling the procedure!
DO NOT call a procedure like this:
Swap(x, 4 );
Swap(5+x, y);