Call-by-Value: Understanding the Limitations
Consider this call-by-value example where we attempt to modify the value of input parameters within a function:
#include <iostream> using namespace std; void changeValue(int value); int main() { int value = 5; changeValue(value); cout << "The value is : " << value << "." << endl; return 0; } void changeValue(int value) { value = 6; }
Surprisingly, the output remains 5 despite our effort to change it to 6. This behavior stems from the fundamental principle of call-by-value in C/C .
The Essence of Call-by-Value
In call-by-value, a copy of the original variable is passed to the function as an argument. Any modifications made to this copy within the function remain confined to that local scope and do not affect the original variable.
In our example, the function changeValue receives a copy of value from main(). Any changes made to this copy do not impact the original value variable.
The Solution: Pass-by-Reference
To modify the original variable from within a function, we must employ pass-by-reference. In C/C , this is denoted as follows:
void changeValue(int &value);
By using & in the function signature, we create a reference (alias) to the original variable. Any changes made to the reference also modify the original variable.
Pass-by-Reference Example
void changeValue(int &value) { value = 6; }
Now, when we call changeValue in main(), a reference to value is passed to the function, allowing it to modify the original value:
int main() { int value = 5; changeValue(value); cout << "The value is : " << value << "." << endl; return 0; }
In this scenario, the output correctly reflects the modified value: 6.
The above is the detailed content of Why Doesn't Call-by-Value Modify the Original Variable?. For more information, please follow other related articles on the PHP Chinese website!