Pass by Reference Using Pointers

Learn what pass by reference is and how to implement it.

Introduction

Pass by reference uses pointers to pass data from one function to another. Instead of sharing a variable by performing a copy, we can share its memory address with the caller function.

A pointer holds a memory address, so our arguments will be pointers when we want to implement pass by reference.

Pass by reference has the following advantages:

  • Data is no longer copied, which saves execution time.
  • The changes made by the callee are visible inside the called function. We say the changes made by the callee get propagated back to the caller. It happens because we’re no longer performing copies since we’re sharing the address of the actual variable and changing it through the pointer.

Motivating example

Let’s go back to one of our motivating examples. The main function passes x by value to change and x is still 3 in main, after the function call. The main function doesn’t see that change modified x because the x from main and the x from change are different variables.

Run the code and confirm it isn’t working correctly, and x remains unchanged in main.

Get hands-on with 1200+ tech skills courses.