Call by value and Call by reference

There are two method to pass the data into the function in C language

  • Call by value
  • Call by reference

Call by value

  • In call by value method of passing the value of the actual parameters is copied into the formal parameters.
  • In C language call by value to pass arguments by default.
  • In Call by value the value of the actual parameter cannot modify by the formal parameter.
  • Different memory is allocated for actual and formal parameters in call by value, since the value of the actual parameter is copy into the formal parameter.

Let’s see the example of call by value in C language

#include <stdio.h>  
void swap(int , int); //prototype of the function   
int main()  
{  
    int a = 10;  
    int b = 20;   
    printf("Before swapping the values a = %d, b = %d\n",a,b);  
    swap(a,b);  
    printf("After swapping values a = %d, b = %d\n",a,b); 
}  
void swap (int a, int b)  
{  
    int temp;   
    temp = a;  
    a=b;  
    b=temp;  
    printf("After swapping values  a = %d, b = %d\n",a,b);  
}

Output

Before swapping the values a = 10, b = 20
After swapping values a = 20, b = 10
After swapping values  a = 10, b = 20

Call by Reference

  • In C language copied the values of variables the address of the variables is used and it is known as call by reference.
  • In call by reference the actual parameters can be modified by changing the formal parameters since then the actual parameters is passed.
  • Actual parameters and formal parameters both the memory allocation are identical.
  • In call by reference the function are performed on the value and they stored at the address of the actual parameters, and the modified value are stored at the same address.

Let’s see the example of call by reference in C language

#include <stdio.h>  
void swap(int *, int *);    
int main()  
{  
    int a = 10;  
    int b = 20;   
    printf("Before swapping the values a = %d, b = %d\n",a,b);  
    swap(&a,&b);  
    printf("After swapping values  a = %d, b = %d\n",a,b);  
}  
void swap (int *a, int *b)  
{  
    int temp;   
    temp = *a;  
    *a=*b;  
    *b=temp;  
    printf("After swapping values a = %d, b = %d\n",*a,*b);    
}

Output

Before swapping the values a = 10, b = 20
After swapping values a = 20, b = 10
After swapping values a = 20, b = 10

Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

The Technical Funda
Average rating:  
 0 reviews