08 Feb Call by Reference in C++
In Call by Reference, the address of the actual parameter is passed to the function. This means changes made to the formal parameter inside the function do affect the actual parameter. It’s used when you want the function to modify the original data. To pass the address, use the address-of operator &.
Let us understand what are the 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 Reference in C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Call by Reference in C++ // Code by Studyopedia #include <iostream> using namespace std; void changeValue(int *x) { *x = 10; // This change will affect the actual parameter cout << "Value = " << *x << endl; } int main() { int a = 5; cout << "Value of a (before) = " << a << endl; changeValue(&a); // Output is 10 since the original value changed cout << "Value of a (after) = " << a << endl; // Output is 10 return 0; } |
Here is the output:
1 2 3 4 5 |
Value of a (before) = 5 Value = 10 Value of a (after) = 10 |
This C++ code demonstrates a call-by-reference mechanism. The changeValue function modifies the value of its pointer parameter, affecting the actual argument a in the main function. It prints the value of a before and after the function call, showing the change (from 5 to 10). The original variable a is updated because the function operates on its reference.
In Call by Reference, the address of the actual parameter is passed to the function. Changes made to the parameter inside the function do affect the original value.
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