Difference between Call by value and Call by Reference

Call by value

  • Call by value method copies the value of a argument into that function's formal parameter. 
  • Changes made to the main function parameter therefore don't affect the argument.In this process of moving parameters, real parameter values are copied to the formal parameters of the function, and the parameters are stored at different memory locations. 
  • So any changes made within functions are not expressed in the caller's actual parameters.

Call by reference

  • Call by reference method copies an argument's address into the formal parameter. 
  • The address is used in this process to access the actual argument used in the call to the function. This means that parameter shifts alter the passing argument.
  • The allocation of memory is the same as the actual parameters in this method. 
  • All function operation is done on the value stored at the address of the actual parameter, and the modified value is stored at the same address.
Call by value and Call by reference


Example of a Call by Value method

#include<stdio.h>
void fun(int x)
{
x=x+5;
} 
int main()
{
int a=10;
printf("Before calling\na=%d",a);
fun(a);
printf("\n\nAfter calling\na=%d",a);
return 0;
}

/* Call By Value in C Example */

#include <stdio.h>

// Function Declaration
void CallByValue(int , int );          

int main()
{
  int a, b;

  printf ("\nPlease Enter 2 Integer Values\n");
  scanf("%d %d", &a, &b);
  
  printf("\nBefore Calling CallByValue() Function A = %d and B = %d", a, b);
  
  CallByValue(a, b);   

  printf(" \nAfter Calling CallByValue From Main() A = %d and B = %d", a, b);                      
}

void CallByValue(int a, int b)  
{
  a = a * 10;
  b = b * 20;

  printf(" \nFrom the CallByValue() Function A = %d and B = %d", a, b);    
}

Output

Before Calling CallByValue() Function A = 5 and B = 10
From the CallByValue() Function A = 25 and B = 50
After Calling CallByValue From Main() A = 5 and B = 10

Example of a Call by Reference method

#include <stdio.h>
// Function Declaration
void Swap(int *, int *);          

int main()
{
  int a, b;

  printf ("Please Enter 2 Integer Values");
  scanf("%d %d", &a, &b);

  printf("\nBefore Swap  A = %d and B = %d", a, b);

  Swap(&a, &b);   

  printf(" \nAfter Swapping From Main() A = %d and B = %d", a, b);                      
}

void Swap(int *x, int *y)
  int Temp;
  Temp = *x;
  *x = *y;
  *y = Temp;

  /*
  
  *x = 20;
  *y = 40;

  */

  printf(" \nAfter Swapping A = %d and B = %d", *x, *y);
}

Output

Please Enter 2 Integer Values
Before Swap  A = 10 and B = 20
After Swapping  A = 20 and B = 10
After Swapping From Main() A = 20 and B = 10

1 Comments

  1. sir ji fun without argument & without return value ka simple ex bateo

    ReplyDelete
Previous Post Next Post