Using a Pointer to Create a Call-by-Reference

chinmay.sahoo

New member
Even though C++’s default parameter-passing convention is call-by-value, it is possible to manually create a call-by-reference by passing the address of an argument (i.e., a pointer to the argument) to a function. It will then be possible for code inside the function to change the value of the argument outside of the function. You saw an
example of this in the preceding chapter when the passing of pointers was discussed. As you know, pointers are passed to functions just like any other values. Of course, it is necessary to declare the parameters as pointer types .

To see how passing a pointer allows you to manually create a call-by-reference, examine this version of swap( ). It exchanges the values of the two variables pointed to by its arguments.

Code:
void swap(int *x, int *y)
{
int temp;
temp = *x; // save the value at address x
*x = *y; // put y into x
*y = temp; // put x into y
}


The *x and the *y refer to the variables pointed to by x and y, which are the addresses of the arguments used to call the function. Consequently, the contents of the variables used to call the function will be swapped.
Since swap( ) expects to receive two pointers, you must remember to call swap( ) with the addresses of the variables you wish to exchange. The correct method is shown in this program:

Code:
#include <iostream>
using namespace std;
// Declare swap() using pointers.
void swap(int *x, int *y);
int main()
{
 
Back
Top