0 votes
140 views
in C programming by (98.9k points)
edited
Explain the difference between function call by value and function call by reference with suitable programmes.

1 Answer

0 votes
by (98.9k points)
edited by
 
Best answer
Sr. No Call by value Call by reference
1 In this case the value of the parameters is passed to the called function In this case the reference of the variable is passed to the function by passing the address of the parameters
2 In this case the actual parameters are not accessible by the called function In this case , as the address of the variables are available , the called function can access the actual parameters
3 This is implemented by using simple variable names This is implemented by the use of pointer variables
4 The actual parameters remain unchanged The actual parameters can be  altered if required 

 


Example 

Swapping the values of the two variables

Call by Value Example

#include <stdio.h>  
void swap(int , int); //prototype of the function   
int main()  
{  
    int a = 10;  
    int b = 20;   
    printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main  
    swap(a,b);  
    printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do not change by changing the formal parameters in call by value, a = 10, b = 20  
}  
void swap (int a, int b)  
{  
    int temp;   
    temp = a;  
    a=b;  
    b=temp;  
    printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b = 10   
}  

 Call by reference Example

#include <stdio.h>  
void swap(int *, int *); //prototype of the function   
int main()  
{  
    int a = 10;  
    int b = 20;   
    printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main  
    swap(&a,&b);  
    printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do change in call by reference, a = 10, b = 20  
}  
void swap (int *a, int *b)  
{  
    int temp;   
    temp = *a;  
    *a=*b;  
    *b=temp;  
    printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20, b = 10   
}  

 


Related questions

0 votes
1 answer 112 views
0 votes
1 answer 140 views

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

554 users

...