Understanding Call-by-Value in C
In this call-by-value example, a function called changeValue() takes an integer argument, which represents a copy of the actual argument passed from the main() function. When the function changes the value of the argument to 6, it modifies the copy and not the original value stored in the main() function.
This is because call-by-value creates a new copy of the argument and passes it to the function. Therefore, any changes made to the copy inside the function will not affect the original value.
Solving the Issue Using Call-by-Reference
To modify the original argument sent from main(), we need to use call-by-reference. This involves passing a reference (an alias) to the actual argument, rather than a copy.
In the example, this can be achieved by changing the changeValue() function signature to:
void changeValue(int &value)
By using ampersand (&) before the argument type, we indicate that the function receives a reference to the original variable. Any changes made to the reference will directly affect the original argument in main().
Revised Code:
#includeusing 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; }
With this change, when changeValue() sets the reference to 6, the original value in main() will be changed to 6, resulting in the output "The value is : 6.".
The above is the detailed content of How Does Call-by-Value Affect Argument Modification in C ?. For more information, please follow other related articles on the PHP Chinese website!