Call by Value in C
The call by value method of passing parameters to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the actual argument.
By default, C language uses the call by value method to pass parameters. Generally, this means that code within a function cannot alter the arguments used to call the function. The swap() function is defined as follows:
/* Function definition */
void swap(int x, int y)
{
int temp;
temp = x; /* Save the value of x */
x = y; /* Assign y to x */
y = temp; /* Assign temp to y */
return;
}
Now, let's call the swap() function by passing actual parameters:
Example
#include <stdio.h>
/* Function declaration */
void swap(int x, int y);
int main ()
{
/* Local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* Calling a function to swap the values */
swap(a, b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
When the above code is compiled and executed, it produces the following result:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 100
After swap, value of b : 200
The above example demonstrates that although the values of a and b are changed inside the function, the actual values of a and b remain unchanged.