In C++, there are two primary ways to pass arguments to a function: call by value and call by reference. Understanding the difference between these two methods is crucial for effective programming.
Call by value is a method where the actual value of the argument is passed to the function. The function creates a copy of the argument and works with that copy, leaving the original value unchanged.
• Copy Creation: When a value is passed to the function, a new copy of the variable is created in the function’s stack memory.
• No Side Effects: Any changes made to the parameter within the function do not affect the original argument used in the caller method, such as main().
<#include <iostream>>
using namespace std;
void modifyValue(int val) {
val = 100; // This will not change the original value
}
int main() {
int num = 50;
cout << "Before function call: " << num << endl;
modifyValue(num); // Passing by value
cout << "After function call: " << num << endl;
return 0;
}
Before function call: 50
After function call: 50
Call by reference is a method where the reference (or address) of the argument is passed to the function. This allows the function to modify the original variable directly.
• Shared Address Space: The function receives the memory address of the argument. Both the actual argument in the caller and the parameter in the function point to the same memory location.
• Side Effects: Any change made to the parameter within the function is reflected in the original argument, affecting the caller method.
<#include <iostream>>
using namespace std;
void modifyValue(int &ref) {
ref = 100; // This will change the original value
}
int main() {
int num = 50;
cout << "Before function call: " << num << endl;
modifyValue(num); // Passing by reference
cout << "After function call: " << num << endl;
return 0;
}
Before function call: 50
After function call: 100