Q: Briefly discuss the concept of βCall by valueβ and βCall by referenceβ. Give example code in C for each. Support your code with suitable comments.
Concept of "Call by Value" and "Call by Reference":
Call by Value:
- In "Call by Value," the actual value of the argument is passed to the function.
- The function operates on a copy of the argument, meaning that changes made to the parameter inside the function do not affect the original variable.
Example of Call by Value:
#include// Function that takes an integer as argument and modifies itvoid addTen(int x) {x = x + 10; // Modify the local copy of the argumentprintf("Inside function: %d\n", x); // Prints modified value inside function}int main() {int num = 5;printf("Before function call: %d\n", num); // Prints original value of numaddTen(num); // Call the function with numprintf("After function call: %d\n", num); // Prints original value of num (unchanged)return 0;}Output:
Before function call: 5 Inside function: 15 After function call: 5- Here,
numremains 5 after the function call, demonstrating that the original value is unaffected.
2. Call by Reference:
- In "Call by Reference," the memory address (reference) of the argument is passed to the function.
- This means the function can directly modify the original variable because it works with the memory location of the argument.
Example of Call by Reference:
#include
// Function that takes a pointer to an integer (reference) as argument
void addTen(int *x) {
*x = *x + 10; // Modify the value at the address pointed by x
printf("Inside function: %d\n", *x); // Prints modified value inside function
}
int main() {
int num = 5;
printf("Before function call: %d\n", num); // Prints original value of num
addTen(#); // Pass the address of num to the function
printf("After function call: %d\n", num); // Prints modified value of num
return 0;
}
Output:
Before function call: 5
Inside function: 15
After function call: 15
In "Call by Reference," the memory address (reference) of the argument is passed to the function.
This means the function can directly modify the original variable because it works with the memory location of the argument.
Here, num is modified to 15, demonstrating that the original variable is directly changed because we passed a reference (address) to the function.
Summary:
- Call by Value: The function receives a copy of the argument, and changes inside the function do not affect the original variable.
- Call by Reference: The function receives the memory address of the argument, and changes inside the function directly modify the original variable.
Comments
Leave a Comment
Your email address will not be published. Required fields are marked *