- Asked 8/16
- 2073 Chaitra · 3 marks
- 2070 Chaitra · 4 marks
- 2070 Asar · 2 marks
- 2069 Chaitra · 4 marks
- 2072 Chaitra · 6 marks
- 2069 Asar · 6 marks
- 2067 Asar · 6 marks
- 2067 Asoj · 3 marks
Call by value versus call by reference
Short answer
Call by value passes a copy of arguments; changes inside the function do not affect the caller. Call by reference passes the address (pointer), so modifications directly alter the original variables.
Differentiate between call by value and call by reference (pass by value and pass by reference) with suitable example.
| Call by value | Call by reference |
|---|---|
| Copies of the actual arguments are passed | Addresses of the actual arguments are passed |
| Formal parameters are ordinary variables | Formal parameters are pointers |
| Changes in the function do not affect the caller's variables | Changes are made on the caller's variables |
| Uses extra memory for copies | No copy of data is made; saves memory for large data |
Call: swap(x, y) | Call: swap(&x, &y) |
| Safe: original data is protected | Original data can be changed (risky) |
C itself always passes by value; "call by reference" is obtained by passing pointers.
#include <stdio.h>
void swap_val(int a, int b)
{
int t = a; a = b; b = t;
printf("Inside swap_val: a=%d b=%d\n", a, b);
}
void swap_ref(int *a, int *b)
{
int t = *a; *a = *b; *b = t;
}
int main(void)
{
int x = 10, y = 20;
swap_val(x, y);
printf("After call by value: x=%d y=%d\n", x, y);
swap_ref(&x, &y);
printf("After call by reference: x=%d y=%d\n", x, y);
return 0;
}
Output:
Inside swap_val: a=20 b=10
After call by value: x=10 y=20
After call by reference: x=20 y=10
swap_val swaps only its local copies, so x and y are unchanged in main. swap_ref uses the addresses, so the values are really exchanged.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Pointers in pass by reference; 2D array · Computer Programming, chapter 9
- Namespace with pass by reference program · Object Oriented Programming, chapter 2
- OS abstraction, extended machine, system call · Operating System, chapter 1
- Cost vs value; factors affecting valuation · Construction Management, chapter 13
- Francis versus Kaplan applicability · Power Plant Design, chapter 3