C Program to Swap Two Numbers using Call by Value
This program swaps two numbers in C using the concept of call by value. It demonstrates how functions work when copies of variables are passed instead of their memory addresses.
Concept Overview
In call by value, the actual values of variables are copied into the function parameters. Any changes made to the parameters inside the function do not affect the original variables in the calling function.
Program
C
#include <stdio.h>
// Function to swap two numbers using call by value
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
int main() {
int a = 10, b = 20;
printf("Before swap, value of a : %d\n", a);
printf("Before swap, value of b : %d\n", b);
swap(a, b);
printf("After swap, value of a : %d\n", a);
printf("After swap, value of b : %d\n", b);
return 0;
}
Output
Before swap, value of a : 10 Before swap, value of b : 20 After swap, value of a : 10 After swap, value of b : 20
Explanation
- The function `swap()` takes two integer arguments by value — meaning copies of the original variables are passed.
- Inside the function, the values are swapped using a temporary variable `temp`.
- However, since only copies are modified, the original variables `a` and `b` in `main()` remain unchanged.
- This demonstrates that in call by value, the function cannot alter the actual arguments.
Note: To actually swap the values, you must use call by reference with pointers instead of call by value.
Codecrown