The parameters can be passed in two ways during function calling,
- Call by value
- Call by reference
Call by value
- In call by value, the values of actual parameters are copied to their corresponding formal parameters.
- So the original values of the variables of calling function remain unchanged.
- Even if a function tries to change the value of passed parameter, those changes will occur in formal parameter, not in actual parameter.
Example:
#include <stdio.h>
void swap(int, int);
void main()
{
int x, y;
printf("Enter the value of X & Y:");
scanf("%d%d", &x, &y);
swap(x, y);
printf(“\n Values inside the main function”);
printf(“\n x=%d, y=%d”, x, y);
}
void swap(int x,int y) {
int temp;
temp=x;
x=y;
y=temp;
printf(“\n Values inside the swap function”);
printf("\n x=%d y=%d", x, y);
}
Output:
Enter the value of X & Y: 3 5
Values inside the swap function
X=5 y=3
Call by Reference
- In call by reference, the address of the actual parameters is passed as an argument to the called function.
- So the original content of the calling function can be changed.
- Call by reference is used whenever we want to change the value of local variables through function.
Example:
#include <stdio.h>
void swap(int *, int *);
void main()
{
int x,y;
printf("Enter the value of X & Y:
scanf("%d%d", &x, &y);
swap(&x, &y);
printf(“\n Value inside the main function”);
printf("\n x=%d y=%d", x, y);
}
void swap(int *x, int *y) {
int temp;
temp=*x;
*x=*y;
*y=temp;
printf(“\n Value inside the swap function”);
printf("\n x=%d y=%d", x, y);
}
Output:
Enter the value of X & Y: 3 5
Value inside the swap function
X=5 y=3
Value inside the main function
X=5 y=3