Summary: in this tutorial, you’ll learn how to pass arguments to a function by references using pointers and address operator ( & ).
In the pass-by-value tutorial, you learned that when passing an argument to a function, the function works on the copy of that argument. Also, the change that function makes to the argument doesn’t affect the original argument.
Sometimes, you want to change the original variables passed to a function. For example, when you sort an array in place, you want to swap the values of two elements. In this case, you need to use the pass-by-reference.
When you pass an argument to a function by reference, the function doesn’t copy the argument. Instead, it works on the original variable. Therefore, any changes that the function makes to the argument also affect the original variable.
To pass an argument to a function by reference, you use the indirection operator ( * ) and address operator ( & ).
The following example illustrates how the pass-by-reference works:
Code language: C++ (cpp)#include void swap(int *x, int *y); int main() < int x = 10, y = 20; printf("Before swap:x =%d, y=%d\n", x, y); // swap x and y swap(&x, &y); printf("After swap:x=%d, y=%d\n", x, y); > void swap(int *x, int *y) < int tmp = *x; *x = *y; *y = tmp; >
Code language: plaintext (plaintext)Before swap:x =10, y=20 After swap:x=20, y=10
First, define a function swap() that swap values of two arguments:
Code language: C++ (cpp)void swap(int *x, int *y);
The arguments x and y are integer pointers will point to the original variables.
Second, swap values of the variables that the poiters points to inside the swap() function definition:
Code language: C++ (cpp)void swap(int *x, int *y) < int tmp = *x; *x = *y; *y = tmp; >
To swap values, we use a temporary variable ( temp ) to hold the value of the first argument ( *x ), assign the value of the second argument to the first one and assigns the value of the temp to the second argument ( *y ).
Third, define two variables in the main() function and display their values:
Code language: C++ (cpp)int x = 10, y = 20; printf("Before swap:x =%d, y=%d\n", x, y);
Fourth, call the swap() function and pass the memory addresses of the variable x and y :
Code language: C++ (cpp)swap(&x, &y);
Finally, display the values of both variables x and y after the swap:
Code language: C++ (cpp)printf("After swap:x=%d, y=%d\n", x, y);