Call by value example:
#include <stdio.h>
void fun_call_by_value(int a, int b)
{
int t;
t = a;
a = b;
b = t;
/* Here a and b will act as a local variable as t. So the change we have done here is last
only in this function. So there is no changes at the caller side value of a and b. */
}
int main()
{
int a = 10, b = 20;
printf(" a = %d and b = %d\n", a, b);
fun_call_by_value(a, b); //try to swap a with b.
printf(" a = %d and b = %d\n", a, b);
return 0
}
Here out put will be same:
1st print: a = 10 and b = 20
2nd print: a = 10 and b = 20
Call by reference : Here we will be sending the address of the variable, and if we perform any operation on those variable it will reflect at the source also.
Example:
#include <stdio.h>
void fun_call_by_reference(int *a, int *b)
{
int t;
t = *a;
*a = *b;
*b = t;
/* Here *a and *b (represent the value at a and b). So the change we have done here will be directly
affecting at it source address. So any changes will reflect at the calling funtion. */
}
int main()
{
int a = 10, b = 20;
printf(" a = %d and b = %d\n", a, b);
fun_call_by_reference(&a, &b); //try to swap a with b.
printf(" a = %d and b = %d\n", a, b);
return 0
}
Here out put will not be the same:
1st print: a = 10 and b = 20
2nd print a = 20 and b = 10
Try exectuting these two program and see the result.
Hope your dought is clear now :)