In General, there are three methods of passing arguments. We pass arguments to a function during its call

  1. Pass by Reference
  2. Pass by value
  3. Pass by constant

What is pass by reference?

Pass by reference is a method of calling a function by passing the reference of a variable in the function’s arguments. The function copies the reference of an argument into the formal parameters. Changes made to the values of the function’s parameters will also affect the values of passed arguments.

Code Example:

Here is the code example of passing the arguments by reference in C. In this program, we swap two values by calling a function through pass by reference; after that, we will discuss the changes in the values. Below program is successfully compiled, and the output is also shown below.

#include <stdio.h>

void swapFunction(int *a, int *b);
 
int main () {
    
   int value_1 = 100;
   int value_2 = 200;
 
   printf("value of value-1 : %d\n", value_1 );
   printf("value of value-2 : %d\n", value_2 );

   swapFunction(&value_1, &value_2);
 
   printf("After swapping, value of value-1 : %d\n", value_1 );
   printf("After swapping, value of value-2 : %d\n", value_2 );
 
   return 0;
}
void swapFunction(int *a, int *b) {

   int temp;
   temp = *a;
   *a = *b;
   *b = temp;
  
   return;
}

Result

Result

Code Explanation

In the above program, we pass the arguments through pass by reference. The procedure for pass by reference is that we use reference sign (&) with a variable in the function’s arguments during a call, and also use steric (*) symbol in function’s parameter variable.

   printf("After swapping, value of value-1 : %d\n", value_1 );
   printf("After swapping, value of value-2 : %d\n", value_2 );

In the above two lines of code, you have noticed that there is a swap of values between variable value_1 and variable value_2. But we swapped variable a and b by calling the function.

Why using by Reference?

The reason is that when we use pass by reference, then the changes in values under function body will also affect the values outside. Reference is a memory location; when we pass by reference, subsequently the memory location will be copied to the function’s parameters. Now changes in the values of these parameters will also overwrite the previous values.

Related Articles
Last modified: May 18, 2019

Comments

Write a Reply or Comment

Your email address will not be published.