Call by Reference Function in C


In C programming, call by reference is a method of passing arguments to a function where the function receives the memory address of the variables passed as arguments, rather than their values. This means that any changes made to the variables within the function affect the original variables.

The basic syntax for passing arguments by reference in C is as follows:

        Syntax :
           return_type function_name ( type *variable_name )
           {
                 // body of Statement ;
           }

Here, the return_type specifies the data type of the value that the function will return, the function_name is the name of the function, and the variable_name is the name of the variable being passed to the function. The * before the variable name indicates that the argument is being passed by reference. Here is an example of a function that swaps the values of two integers passed by reference:

  • The function swap takes two integer pointers x and y as arguments, which holds the memory address of the integers being passed. Inside the function, we create a temporary variable temp and store the value of *x in it. Then, the value of *y is assigned to the memory location pointed by x and the value of temp is assigned to the memory location pointed by y.
  • In the main function, we have two integer variables a and b with initial values. These values get swapped by passing their addresses using the & operator and the effect is observed in the final output.
  • This program demonstrates how to pass arguments to a function by reference, how to access the value stored at the memory location pointed by a pointer, and how to use pointers to modify the values of variables passed to a function.

Source Code

//Call by Reference Function in C Programming
 
#include<stdio.h>
 
void swap(int *x,int *y)
{
   int temp;
   temp=*x;
   *x=*y;
   *y=temp;
}
 
int main()
{
    int a,b;
    printf("\nEnter The Value of A & B : ");
    scanf("%d%d",&a,&b);
    printf("\nBefore Swap  A : %d   | B : %d",a,b);
    swap(&a,&b);
    printf("\nAfter  Swap  A : %d   | B : %d",a,b);
    return 0;
}
 
To download raw file Click Here

Output

Enter The Value of A & B : 10
20

Before Swap  A : 10   | B : 20
After  Swap  A : 20   | B : 10

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C