C Pass By Reference

Summary: in this tutorial, you’ll learn how to pass arguments to a function by references using pointers and address operator (&).

Introduction to pass-by-reference in C

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 (&).

Pass-by-reference example

The following example illustrates how the pass-by-reference works:

#include <stdio.h> 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: C++ (cpp)

Output:

Before swap:x =10, y=20 After swap:x=20, y=10
Code language: plaintext (plaintext)

How it works.

First, define a function swap() that swap values of two arguments:

void swap(int *x, int *y);
Code language: C++ (cpp)

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:

void swap(int *x, int *y) { int tmp = *x; *x = *y; *y = tmp; }
Code language: C++ (cpp)

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:

int x = 10, y = 20; printf("Before swap:x =%d, y=%d\n", x, y);
Code language: C++ (cpp)

Fourth, call the swap() function and pass the memory addresses of the variable x and y:

swap(&x, &y);
Code language: C++ (cpp)

Finally, display the values of both variables x and y after the swap:

printf("After swap:x=%d, y=%d\n", x, y);
Code language: C++ (cpp)

Summary

  • Pass-by-reference allows a function to change the original variable passed to it as arguments.
  • Use indirection operator (*) and address operator (&) to pass arguments to a function by references.
Was this tutorial helpful ?