1 answer
Best answer
Answer: In call by value a copy of the actual argument is passed, so changes inside the function do not affect the caller. In call by reference the address of the argument is passed (using pointers), so the function can change the caller's variables.
| Sr. No. | Call by value | Call by reference |
|---|---|---|
| 1 | The value of each actual parameter is copied into the formal parameter. | The address of each actual parameter is passed to the function. |
| 2 | The called function works on copies and cannot reach the actual parameters. | The called function reaches the actual parameters through their addresses. |
| 3 | Formal parameters are ordinary variables, e.g. void swap(int x, int y). | Formal parameters are pointers, e.g. void swap(int *x, int *y), called as swap(&a, &b). |
| 4 | Actual parameters remain unchanged. | Actual parameters can be changed. |
| 5 | Safer when the original data must not change. | Useful when a function must return more than one result. |
Example: swapping two variables
Call by value:
#include <stdio.h>
void swap(int x, int y) /* call by value: copies are received */
{
int temp;
temp = x;
x = y;
y = temp;
printf("Inside swap: x = %d, y = %d\n", x, y);
}
int main()
{
int a = 10, b = 20;
printf("Before swap in main: a = %d, b = %d\n", a, b);
swap(a, b);
printf("After swap in main: a = %d, b = %d\n", a, b); /* unchanged: a = 10, b = 20 */
return 0;
}Output (actual run):
Before swap in main: a = 10, b = 20
Inside swap: x = 20, y = 10
After swap in main: a = 10, b = 20Call by reference:
#include <stdio.h>
void swap(int *x, int *y) /* call by reference: addresses are received */
{
int temp;
temp = *x;
*x = *y;
*y = temp;
printf("Inside swap: *x = %d, *y = %d\n", *x, *y);
}
int main()
{
int a = 10, b = 20;
printf("Before swap in main: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("After swap in main: a = %d, b = %d\n", a, b); /* changed: a = 20, b = 10 */
return 0;
}Output (actual run):
Before swap in main: a = 10, b = 20
Inside swap: *x = 20, *y = 10
After swap in main: a = 20, b = 10In call by value only the copies x and y are swapped, so a and b in main stay 10 and 20. In call by reference the function swaps the values stored at the addresses of a and b, so main prints a = 20, b = 10.
Your answer
Log in or create a free account to answer this question.