Is there a way to return by reference in a function, for example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include<iostream>
#include<stdio.h>
usingnamespace std;
int sum(int num1, int num2)
{
return num1 + num2 ;
}
int main()
{
int num1, num2, s;
cout<<"\nEnter two numbers: ";
cin>>num1>>num2;
s = sum(num1, num2);
cout<<"\nSum of "<<num1<<" and "<<num2<<" is "<<s;
return 0;
}
There's something you should be aware of when returning L-value references: don't return temporary storage, like this:
1 2 3 4 5
int &Function( )
{
int X;
return( X ); // Oops.
}
Once "Function( )" returns, "X" will be popped from the stack, thereby leaving the reference returned by the function in an invalid sate and attempting to access the referent is undefined behavior.
A simple solution is to declare "X" as static.
1 2 3 4 5
int &Function( )
{
staticint X;
return( X ); // OK
}
Since static storage declared within functions remains even after the function has finished, returning a reference to the aforementioned storage is deemed safe due to the extended lifetime of the storage. However, since the static storage is only directly accessible to the function in which the storage is declared, the reference becomes the only means of access once the function has ended.