What is pass by reference in C language?

CServer Side ProgrammingProgramming

Pass by reference in C programming language is the addresses which are sent as arguments.

Algorithm

An algorithm is given below to explain the working of pass by value in C language.

START
Step 1: Declare a function with pointer variables that to be called.
Step 2: Declare variables a,b.
Step 3: Enter two variables a,b at runtime.
Step 4: Calling function with pass by reference.
jump to step 6
Step 5: Print the result values a,b.
Step 6: Called function swap having address as arguments.
   i. Declare temp variable
   ii. Temp=*a
   iii. *a=*b
   iv. *b=temp
STOP

Example program

Following is the C program to swap two numbers using pass by reference −

 Live Demo

#include<stdio.h>
void main(){
   void swap(int *,int *);
   int a,b;
   printf("enter 2 numbers");
   scanf("%d%d",&a,&b);
   printf("Before swapping a=%d b=%d",a,b);
   swap(&a, &b);
   printf("after swapping a=%d, b=%d",a,b);
}
void swap(int *a,int *b){
   int t;
   t=*a;
   *a=*b; // *a = (*a + *b) – (*b = * a);
   *b=t;
}

Output

When the above program is executed, it produces the following result −

enter 2 numbers 10 20
Before swapping a=10 b=20
After swapping a=20 b=10

Let’s take another example to know more about pass by reference.

Example

Following is the C program to increment value by 5 for every call by using call by reference or pass by reference.

 Live Demo

#include <stdio.h>
void inc(int *num){
   //increment is done
   //on the address where value of num is stored.
   *num = *num+5;
   // return(*num);
}
int main(){
   int a=20,b=30,c=40;
   // passing the address of variable a,b,c
   inc(&a);
   inc(&b);
   inc(&c);
   printf("Value of a is: %d\n", a);
   printf("Value of b is: %d\n", b);
   printf("Value of c is: %d\n", c);
   return 0;
}

Output

When the above program is executed, it produces the following result −

Value of a is: 25
Value of b is: 35
Value of c is: 45
raja
Published on 11-Mar-2021 12:46:03
Advertisements