In C programming language, function arguments can be passed by value or by reference.
In call by value, the function receives a copy of the argument’s value, and any modifications made to the parameter within the function are not reflected outside of the function. In other words, changes made to the value of the parameter within the function do not affect the value of the original variable passed as an argument.
Here is an example of a function that takes two integer arguments and performs a multiplication operation using call by value:
int multiply(int x, int y) {
int result = x * y;
return result;
}
int main() {
int a = 10, b = 20, c;
c = multiply(a, b);
printf("%d", c);
return 0;
}
In this example, the multiply() function takes two integer arguments by value, performs a multiplication operation, and returns the result. The main() function then calls multiply() with two variables a and b and stores the result in variable c. Any modifications made to the variables within the multiply() function do not affect the values of a and b in the main() function.
In call by reference, the function receives a reference (or pointer) to the argument, and any modifications made to the parameter within the function are reflected outside of the function. In other words, changes made to the value of the parameter within the function will affect the value of the original variable passed as an argument.
Here is an example of a function that takes two integer arguments and performs a swap operation using call by reference:
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a = 10, b = 20;
swap(&a, &b);
printf("a = %d, b = %d", a, b);
return 0;
}
In this example, the swap() function takes two integer arguments by reference, performs a swap operation using pointers, and modifies the values of the variables passed as arguments. The main() function then calls swap() with variables a and b using the address-of operator &, which passes the memory addresses of a and b to swap(). As a result, the values of a and b are swapped, and the modified values are printed out in the main() function.
In summary, call by value passes the actual value of the argument to the function, while call by reference passes a reference (or pointer) to the argument to the function. Call by value is used for simple data types or when the function should not modify the original argument’s value, while call by reference is used when the function needs to modify the original argument’s value or when passing large data structures to the function would be inefficient.