08 Feb Call by Value in C++
In Call by Value, when a function is called, the value of the actual parameter is copied into the formal parameter. This means changes made to the formal parameter inside the function do not affect the actual parameter. It ensures data protection, as the original data remains unchanged.
Let us also understand what are the two types of parameters:
- Actual parameters are the values or variables passed to the function when it is called.
- Formal parameters are the variables defined in the function declaration and definition that receive the values of the actual parameters.
Let us see an example to implement Call by Value in C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> using namespace std; void changeValue(int x) { x = 10; // This change will not affect the actual parameter cout << "Value = " << x << endl; } int main() { int a = 5; cout << "Value of a (before) = " << a << endl; changeValue(a); cout << "Value of a (after) = " << a << endl; // Output is 5 return 0; } |
Here is the output:
1 2 3 4 5 |
Value of a (before) = 5 Value = 10 Value of a (after) = 5 |
The above C++ code demonstrates a call-by-value mechanism. The changeValue function changes the value of its parameter x to 10, but this change does not affect the actual argument a in the main function. Before calling changeValue, the code prints the value of a. After the function call, it prints the value of a again, showing it remains unchanged (still 5).
In Call by Value, a copy of the actual parameter’s value is passed to the function. Changes made to the parameter inside the function do not affect the original value outside the function.
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments