Return by reference
Aug 30, 2018Like the variable alias in passing arguments as reference, the return by reference returns the alias. The return by reference mechanism allows us to write the function on the left hand side of the equality expression. Let's look at the c style of returning address.
int *max(int *n1, int *n2){
if(*n1 > *n2)
return n1;
else
return n2;
}
and the funtion is called as.
*max(&num1, &num2) = 100;
the above call assigns the number 100 to the larger number.
In C++, the same mechanism can be achieved as
int &max(int &n1, int &n2){
if(n1 > n2)
return n1;
else
return n2;
}
and is called as.
max(num1, num2) = 100;
Q. Write a program to read two numbers from the user. Assign the number -1 to the smallest number using return by reference.
#include
using namespace std;
//function to return the reference of smallest number
int &smallest(int &num1, int &num2){
if(num1 < num2)
return num1;
else
return num2;
}
int main(){
int n1,n2;
cout<<"Enter number 1:"<<endl;
cin>>n1;
cout<<"Enter number 2:"<<endl;
cin>>n2;
cout<<"Numbers are :"<<n1<<" and "<<n2<<endl;
smallest(n1,n2) = -1;
cout<<"After calling function Numbers are :"<<n1<<" and "<<n2<<endl;
return 0;
}