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
}