Call by value in C
In call by value, value being passed to the function is locally stored by the function parameter in stack memory location.
If you change the value of function parameter, it is changed for the current function only.
It will not change the value of variable inside the caller method such as main().
Consider a simple program :
void swap(int x, int y);
int main () {
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );//Before swap, value of a :100
printf("Before swap, value of b : %d\n", b );//Before swap, value of b :200
swap(a, b);
printf("After swap, value of a : %d\n", a );//Before swap, value of a :100
printf("After swap, value of b : %d\n", b );//Before swap, value of b :200
return 0;
}
void swap(int x, int y) {
int temp;
temp = x;
x = y;
return;
}
Call by reference in C
In call by reference, original value is modified because we pass reference (address).
Here, address of the value is passed in the function, so actual and formal arguments shares the same address space.
Hence, value changed inside the function, is reflected inside as well as outside the function.
Consider a simple program :
void swap(int *x, int *y);
int main () {
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a ); // Before swap, value of a :100
printf("Before swap, value of b : %d\n", b );// Before swap, value of b :200
swap(&a, &b);
printf("After swap, value of a : %d\n", a );//Before swap, value of a :200
printf("After swap, value of b : %d\n", b );//Before swap, value of b :100
return 0;
}
void swap(int *x, int *y) {
int temp;
temp = *x;
*x = *y;
return;
}
PS:C has only pass by value. The second case here is pass by pointer- which is also pass by value as the value of the pointer is being copied and passed as a value. We get the effect of pass by reference because we use "*" operator explicitly inside the function to get the content of the pointed location. This is different from pass by reference where this is done entirely by the language and not the programmer.