Write a C++ Program to Demonstrate Call by Value and Call by Reference
Function calls in C++ can be done in two primary ways: Call by Value and Call by Reference. These two methods define how arguments are passed to functions and how changes made within a function affect the original data.
Understanding the difference between these two is crucial for controlling data flow, memory usage, and optimizing code performance.
🔹 Call by Value
In Call by Value, the actual value of the argument is passed to the function. A new copy of the variable is created in memory, and all operations within the function affect only the copy, not the original variable.
🔹 Call by Reference
In Call by Reference, the address (or reference) of the variable is passed to the function. Therefore, any change made inside the function **directly modifies the original variable.
✅ C++ Program to Demonstrate Both Concepts
#include <iostream>
using namespace std;
// Function using Call by Value
void callByValue(int a) {
a = a + 10;
cout << "Inside callByValue, value of a: " << a << endl;
}
// Function using Call by Reference
void callByReference(int &b) {
b = b + 10;
cout << "Inside callByReference, value of b: " << b << endl;
}
int main() {
int x = 5, y = 5;
cout << "Initial value of x: " << x << endl;
callByValue(x);
cout << "After callByValue, value of x: " << x << endl;
cout << "\nInitial value of y: " << y << endl;
callByReference(y);
cout << "After callByReference, value of y: " << y << endl;
return 0;
}
🔍 Output Explanation
Initial value of x: 5
Inside callByValue, value of a: 15
After callByValue, value of x: 5
Initial value of y: 5
Inside callByReference, value of b: 15
After callByReference, value of y: 15
As seen above:
- In callByValue, the original variable `x` remains unchanged even after the function call.
- In callByReference, the original variable `y` is modified inside the function, and the change reflects in the `main()` function.
🧠 Why This Matters
- Call by Value is safe and protects the original data, but does not allow modification.
- Call by Reference allows modifications, which is useful for performance (avoiding copying large objects) and when intentional changes are needed.
Comments
Post a Comment