C

In C Programming, A Function Is Called By Reference

Before we get into function calls by reference, it’s important to understand the terminology we’ll be using:
The parameters that appear in function calls are known as actual parameters.
Formal parameters are the parameters found in function declarations.
As an example: We have a function declaration that looks like this:

int sum(int a, int b);

The parameters a and b are formal parameters.
The function is named as follows:

int s = sum(10, 20); //Here 10 and 20 are actual parameters
or 
int s = sum(n1, n2); //Here n1 and n2 are actual parameters

This guide will go over the function call by reference method. If you want to learn more about the call by value method, check out this guide: function call by value.
Let’s get back to business.

What exactly is a Function Call By Reference?

When we call a function by passing the addresses of actual parameters, this is referred to as call by reference. The operation performed on formal parameters affects the value of actual parameters in call by reference because all operations performed on the value stored in the address of actual parameters. It may appear perplexing at first, but the following example will clear your doubts.

Function call by Reference Example

Let’s look at a simple example. Read the comments in the program below.

#include <stdio.h>
void increment(int  *var)
{
    /* Although we are performing the increment on variable
     * var, however the var is a pointer that holds the address
     * of variable num, which means the increment is actually done
     * on the address where value of num is stored.
     */
    *var = *var+1;
}
int main()
{
     int num=20;
     /* This way of calling the function is known as call by
      * reference. Instead of passing the variable num, we are
      * passing the address of variable num
      */
     increment(&num);
     printf("Value of num is: %d", num);
   return 0;
}

Output:

Value of num is: 21

Example 2: Function Call by Reference – Number Swapping

We’re using call by reference to swap the numbers here. Because the swap occurred on the addresses of the variables num1 and num2, the values of the variables have been changed after calling the swapnum() function.

#include 
void swapnum ( int *var1, int *var2 )
{
   int tempnum ;
   tempnum = *var1 ;
   *var1 = *var2 ;
   *var2 = tempnum ;
}
int main( )
{
   int num1 = 35, num2 = 45 ;
   printf("Before swapping:");
   printf("\nnum1 value is %d", num1);
   printf("\nnum2 value is %d", num2);

   /*calling swap function*/
   swapnum( &num1, &num2 );

   printf("\nAfter swapping:");
   printf("\nnum1 value is %d", num1);
   printf("\nnum2 value is %d", num2);
   return 0;
}

Output:

Before swapping:
num1 value is 35
num2 value is 45
After swapping:
num1 value is 45
num2 value is 35

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button