What is call by value and call by reference in C language - Call by value - Call by reference - What is call by value - What is call by reference
What is call by value and call by reference in C language?
In C programming (and many other programming languages), "call by value" and "call by reference" are two ways to pass arguments to functions, each with its own behaviour and implications.
Call by Value:
In call by value, a copy of the actual argument (the value) is passed to the function. Any modifications made to the parameter within the function do not affect the original variable outside the function. Changes made to the parameter inside the function are limited to the function's scope and are discarded once the function execution completes.
Here's an example illustrating call by value:
#include <stdio.h>
void increment(int num) {
num++;
printf("Inside function: %d\n", num);
}
int main() {
int value = 10;
printf("Before function: %d\n", value);
increment(value);
printf("After function: %d\n", value);
return 0;
}
In this example, the value of value inside the main function remains unchanged even though it was modified inside the increment function. The modification is local to the increment function.
Call by Reference:
In call by reference, a reference (i.e., a memory address or pointer) to the actual argument is passed to the function. Any modifications made to the parameter inside the function affect the original variable outside the function, as they both refer to the same memory location.
Here's an example illustrating call by reference using pointers:
#include <stdio.h>
void increment(int *num) {
(*num)++;
printf("Inside function: %d\n", *num);
}
int main() {
int value = 10;
printf("Before function: %d\n", value);
increment(&value);
printf("After function: %d\n", value);
return 0;
}
In this example, the value of value is modified inside the increment function using a pointer. The modification is reflected outside the function, altering the original value of value.
In summary, call by value passes a copy of the value to the function, and call by reference passes a reference to the value (typically using pointers) to the function, allowing modifications to affect the original variable.
Comments
Post a Comment