Write a program to swap two numbers using function using call-by-value method call-by-reference method
|
Write a program to swap two numbers using function using
|
|
Write a program to swap two numbers using function using
|
Answer: with call by value the swap happens only on copies, so the original variables do not change; with call by reference (passing addresses) the originals are swapped.
#include <stdio.h>
void swapValue(int x, int y) { /* call by value */
int t = x;
x = y;
y = t;
printf("Inside swapValue: x = %d, y = %d\n", x, y);
}
void swapRef(int *x, int *y) { /* call by reference */
int t = *x;
*x = *y;
*y = t;
}
int main() {
int a = 10, b = 20;
swapValue(a, b);
printf("After call by value: a = %d, b = %d\n", a, b);
swapRef(&a, &b);
printf("After call by reference: a = %d, b = %d\n", a, b);
return 0;
}
Output:
Inside swapValue: x = 20, y = 10
After call by value: a = 10, b = 20
After call by reference: a = 20, b = 10
Explanation: in call by value, copies of a and b are passed; the function swaps its own copies x and y, which are destroyed when it returns. In call by reference, the addresses &a and &b are passed; using the pointers *x and *y the function changes the original variables.
Log in or create a free account to answer this question.