In C language we can pass arguments to a function using below two ways.
Below is the example of call by value
#includevoid change(int num) { printf("Before adding value inside function num=%d \n",num); num=num+100; printf("After adding value inside function num=%d \n", num); } int main() { int x=100; printf("Before function call x=%d \n", x); change(x);//passing value in function printf("After function call x=%d \n", x); return 0; }
#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
}Consider the following example for the call by reference.
#includevoid change(int *num) { printf("Before adding value inside function num=%d \n",*num); (*num) += 100; printf("After adding value inside function num=%d \n", *num); } int main() { int x=100; printf("Before function call x=%d \n", x); change(&x);//passing reference in function printf("After function call x=%d \n", x); return 0; }
Call by reference Example: Swapping the values of the two variables
#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
}| No. | Call by value | Call by reference |
|---|---|---|
| 1 | A copy of the value is passed into the function | An address of value is passed into the function |
| 2 | Changes made inside the function is limited to the function only. The values of the actual parameters do not change by changing the formal parameters. | Changes made inside the function validate outside of the function also. The values of the actual parameters do change by changing the formal parameters. |
| 3 | Changes made to the parameter are not reflected in the original parameter. | Changes made to the parameters are reflected in the original parameter. |
| 4 | Actual and formal arguments are created at the different memory location | Actual and formal arguments are created at the same memory location |
