C Parameter Passing – Call by Value & Call by Reference
Call by Value:
In call by value, a copy of the actual argument (the value or expression passed to the function) is passed to the function parameter. Changes made to the function parameter do not affect the original argument. It is the default method of parameter passing in C.
Example:
#include <stdio.h>
// Function that swaps two integers using call by value
void swapByValue(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
// Call the function by value
swapByValue(x, y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
In this example, swapByValue
receives copies of x
and y
, swaps them inside the function, but the original x
and y
in main
remain unchanged.
Call by Reference:
In call by reference, the memory address (pointer) of the actual argument is passed to the function parameter. Changes made to the function parameter directly affect the original argument. In C, this is achieved using pointers or by passing an array.
Example using Pointers:
#include <stdio.h>
// Function that swaps two integers using call by reference (pointers)
void swapByReference(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
// Call the function by reference
swapByReference(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
In this example, swapByReference
receives pointers to x
and y
, allowing it to directly modify the original variables.
Call by value is safer and prevents unintended modification of original data, while call by reference provides more direct access to data but requires careful handling to avoid unintended side effects. The choice between these methods depends on your specific requirements and design considerations.