What is meant by pass by reference? How can we pass arguments by reference by using reference variable? Illustrate with example.

This answer is restricted. Please login to view the answer of this question.

Login Now

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in.

To pass a value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.

#include <stdio.h>

void swap(int *x, int *y) {

   int temp;

   temp = *x;
   *x = *y;
   *y = temp;
  
   return;
}

int main () {

   int a = 100;
   int b = 200;
 
   printf("Before swap, value of a : %d\n", a );
   printf("Before swap, value of b : %d\n", b );
 
   swap(&a, &b);
 
   printf("After swap, value of a : %d\n", a );
   printf("After swap, value of b : %d\n", b );
 
   return 0;
}

c++ code:

#include<iostream>
using namespace std;

void swap(int *x, int *y) {

   int temp;

   temp = *x;
   *x = *y;
   *y = temp;
  
   return;
}

int main () {

    int a = 100;
    int b = 200;
 
    cout << "Before swap, value of a : " << a << endl;
    cout << "Before swap, value of b : " << b << endl;
 
    swap(&a, &b);
 
    cout << "After swap, value of a : " << a << endl;
    cout << "After swap, value of b : " << b << endl;
 
   return 0;
}

The output of above programs is

Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

It shows that the change has reflected outside the function as well, unlike call by value where the changes do not reflect outside the function.

If you found any type of error on the answer then please mention on the comment or report an answer or submit your new answer.
Leave your Answer:

Click here to submit your answer.

Discussion
0 Comments
  Loading . . .