C++ Call by reference: using pointers

Introduction

While studying functions, you would remember that we used to pass arguments in a function definition. For example,

int func(int a, int b)

Here a and b are those arguments that are passed within the function definition. 

We can also pass the reference of these arguments and compute the desired result. We’ll see the same in this article.

What is call by reference?

We can pass arguments in a function using two ways: 

  1. Call by value
  2. Call by reference

In call by value, we pass the values directly in the function whereas in the call by reference we pass the reference/address of those arguments.

Code:

C++ Code

#include <iostream>
using namespace std;

void callByValue(int x) {
  cout << x << "\n";
}
void callByReference(int & x) {
  cout << x << "\n";
}
int main() {
  int x = 5;
  callByValue(x);
  callByReference(x);
  return 0;
}

Output:

5
5

Here the call-by-value function directly accepts the value of the variable whereas the call-by-reference function accepts the reference/address of the variable.

Now, let’s check how we can implement it using pointers and without pointers

Call by reference: Without using pointers

Code:

C++ Code

#include <iostream>
using namespace std;

void assignValue(int & x) {
  x = 4;
}
int main() {
  int x = 3;
  assignValue(x); // calling function
  cout << x << "\n";
  return 0;
}

Output:

4

Here the assignValue function is accepting addresses as parameters. 

Here on the line “calling function”, we are passing the variable itself, which directly goes to the function definition and uses the address of that variable.

Call By Reference: Using pointers

Code:

C++ Code

#include <iostream>
using namespace std;

void assignValue(int * a) {
  * a = 4;
}
int main() {
  int x = 3;
  assignValue( & x);
  cout << x << "\n";
  return 0;
}

Output:

4

Here while calling assignValue function, we are passing the address of the variable rather than the variable itself. Later to change the value we are accessing the value using the dereference (*) operator.

Since a contains the address of x, any changes done to a will reflect x also.

Special thanks to Yash Mishra for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article