What is the difference between call by value and call by reference in C?
Following are the differences between a call by value and call by reference are:
Call by value | Call by reference | |
---|---|---|
Description | When a copy of the value is passed to the function, then the original value is not modified. | When a copy of the value is passed to the function, then the original value is modified. |
Memory location | Actual arguments and formal arguments are created in separate memory locations. | Actual arguments and formal arguments are created in the same memory location. |
Safety | In this case, actual arguments remain safe as they cannot be modified. | In this case, actual arguments are not reliable, as they are modified. |
Arguments | The copies of the actual arguments are passed to the formal arguments. | The addresses of actual arguments are passed to their respective formal arguments. |
Example of call by value:
void change(int,int);
int main()
{
int a=10,b=20;
change(a,b); //calling a function by passing the values of variables.
printf(“Value of a is: %d”,a);
printf(“\n”);
printf(“Value of b is: %d”,b);
return 0;
}
void change(int x,int y)
{
x=13;
y=17;
}
Output:
Value of a is: 10
Value of b is: 20
Example of call by reference:
void change(int*,int*);
int main()
{
int a=10,b=20;
change(&a,&b); // calling a function by passing references of variables.
printf(“Value of a is: %d”,a);
printf(“\n”);
printf(“Value of b is: %d”,b);
return 0;
}
void change(int *x,int *y)
{
*x=13;
*y=17;
}
Output:
Value of a is: 13
Value of b is: 17
Recent Posts