call by reference and call by value in C++ User define functions is explained with easy words in this tutorial.
Note: Variables x and y on lineĀ number6 are getting the values from line 4 and line4 is getting the values from line 22, and line 22 is getting the values of a and b from line number 19 and 21
Logic
Call by value in C++ – User Define Functions
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 value using user define function - t4tutorials.com #include<iostream> using namespace std; int greature_num(int x ,int y) { if(x>y) { cout<<x<<" Is Greater than "<<y; } else { cout<<y<<" is greater than "<<x; } } int main() { int a,b; cout<<"Enter 1st Number : "; cin>>a; cout<<"Enter 2nd Number : "; cin>>b; greature_num(a,b); } |
Output
Enter 1st Number :
2
Enter 2ndĀ Number :
3
3 is greater than 2
Call by reference in C++ – User Define Functions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //call by value using user define function - t4tutorials.com #include<iostream> using namespace std; int greature_num(int &x ,int &y) { if(x>y) { cout<<x<<" Is Greature than "<<y; } else { cout<<y<<" is greature than "<<x; } } int main() { int a,b; cout<<"Enter 1st Number : "; cin>>a; cout<<"Enter 2nd Number : "; cin>>b; greature_num(a,b); } |
Output
Enter 1st Number :
8
Enter 2ndĀ Number :
9
9 is greater than 8
what is the difference between pass by reference and call by reference?
In C++ and C, call by reference and pass by reference are the same things.
Difference between call by value and call by reference in C++
No. | Pass by value | Pass by reference |
1 | A copy of value is passed to the user define a function. | An address of value is passed to the user define function. |
2 | Changes made inside the user define function is not reflected on other functions. | Changes made inside the user define function is reflected outside the function also. |
3 | Actual and formal parameters will be created in different memory locations. | Actual and formal parameters will be created in same memory locations |
Call by value: Changes made inside the user defined function is not reflected on other functions.
The demo is for variable Y.
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 value using user define function - t4tutorials.com #include<iostream> using namespace std; int sum(int &x ,int y) //&x represents call by refrence //&x receiving 5 from parameter a on line#19 //y receiving 10 from parameter b on line#19 //y represent call by value { x=x+20; y=y+10; cout<<x+y<<endl; } int main() { int a,b; a=5; b=10; sum(a,b); //value of a is passing to &x by reference //value of b is passing to y by value cout<<a<<endl<<b<<endl; } |
Output
45
25
10