“Call by value” and “Call by reference” are two different ways to pass arguments to functions in programming.
Call by Value
In “call by value”, a copy of the actual parameter’s value is passed to the function. This means that any changes made to the parameter inside the function do not affect the original variable.
Example in C:
#include <stdio.h>
// Function that takes an integer by value
void callByValue(int x) {
// Modify the parameter
x = 100;
printf("Inside callByValue, x = %d\n", x);
}
int main() {
int a = 10;
printf("Before callByValue, a = %d\n", a);
// Call the function with 'a' as argument
callByValue(a);
// 'a' is not modified by the function
printf("After callByValue, a = %d\n", a);
return 0;
}
Output:
Before callByValue, a = 10
Inside callByValue, x = 100
After callByValue, a = 10
Call by Reference
In “call by reference”, the address of the actual parameter is passed to the function, allowing the function to modify the original variable directly.
Example in C:
#include <stdio.h>
// Function that takes a pointer to an integer (call by reference)
void callByReference(int *x) {
// Modify the value at the address pointed to by 'x'
*x = 100;
printf("Inside callByReference, *x = %d\n", *x);
}
int main() {
int a = 10;
printf("Before callByReference, a = %d\n", a);
// Call the function with the address of 'a' as argument
callByReference(&a);
// 'a' is modified by the function
printf("After callByReference, a = %d\n", a);
return 0;
}
Output:
Before callByReference, a = 10
Inside callByReference, *x = 100
After callByReference, a = 100
Explanation
- Call by Value: The function
callByValue
receives a copy of the variablea
. Any changes made tox
inside the function do not affecta
in themain
function. - Call by Reference: The function
callByReference
receives a pointer to the variablea
. The function can modify the actual value ofa
by dereferencing the pointerx
(using*x
).
These examples demonstrate how each method passes arguments to functions and how modifications within the function affect the original variables.