Call by reference in C++
In call by reference, original value is modified because we pass
reference (address).
Here, address of the value is passed in the function, so actual and
formal arguments share the same address space. Hence, value
changed inside the function, is reflected inside as well as outside the
function.
1. #include<iostream>
2. using namespace std;
3. void swap(int *x, int *y)
4. {
5. int swap;
6. swap=*x;
7. *x=*y;
8. *y=swap;
9. }
10. int main()
11. {
12. int x=500, y=100;
13. swap(&x, &y); // passing value to function
14. cout<<"Value of x is: "<<x<<endl;
15. cout<<"Value of y is: "<<y<<endl;
16. return 0;
17. }
Output:
Value of x is: 100
Value of y is: 500
Difference between call by value and call by
reference in C++
No Call by value Call by reference
.
1 A copy of value is passed to the function An address of value is pass
function
2 Changes made inside the function is not Changes made inside the f
reflected on other functions reflected outside the function
3 Actual and formal arguments will be Actual and formal argumen
created in different memory location created in same memory loca