a shot of dev knowledge

RELATED TAGS

What is pass by reference?

Definition

Pass by reference revolves around the concept of passing a variable address/pointer as an argument to a function.

Instead of making a copy of the variable in the memory, variable references are passed onto the function and manipulated as required.

It will not save old values. Instead, it will fill new values in those memory spaces.

Let’s take a look at an example.

C++ example

#include <iostream>
using namespace std;

void passByRef(int &a){
  a = 8;
}

int main() {
  int a = 5;
  cout << "Old Value:" <<a << endl;
  passByRef(a);
  cout << "New Value:" <<a << endl;
  return 0;
}
C++ function taking an argument by reference

Below is an illustration explaining the above code.

myFunction() and variable A initially
1 of 3

Behaviour with different languages

C++

In C++, primitive data types (such as int, char, etc.) are pass by value by default. However, they can be passed by reference using the & operator.

The non-primitive data types are pass by reference by default, as the reference to the object is passed to the function.

Java

In Java, all data types are passed by values.

To further enhance your understanding, you can compare this concept with pass by value. Check out this shot for a clearer picture.

Advantages of pass by reference

  • We do not have to make a copy, so pass by reference is quick and efficient
  • Alteration of values is possible directly without the hassle of creating duplicates
  • Avoids confusion when frequent changes would be encountered

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring