for example this function f defined like this :
int f(int x){return x;}
as you know You cant assign a reference to this temporary int :
int& rf=f(2);// this will give an error
but if I redefined my function f like this:
int& f(int x){return x;}
f(2);// so now f(2) is a reference of x, which has been destroyed
so my question is : how can the compiler not let you create a reference to a temporary which will be destroyed after the statment (int the 1st case). and on the other hand it lets you create a reference f(2) to x
while compiler knows that this one will be destroyed after return
.
The return statement should not return a pointer that has the address of a local variable ( sum ) because, as soon as the function exits, all local variables are destroyed and your pointer will be pointing to someplace in the memory that you no longer own.
Objects returned by reference must live beyond the scope of the function returning the reference, or a dangling reference will result. Never return a local variable by reference.
The problem is, we return address of a local variable which is not advised as local variables may not exist in memory after function call is over. So in simple words, Functions can't return arrays in C. However, inorder to return the array in C by a function, one of the below alternatives can be used.
Returning a reference returns by reference. In addition to allowing modification of the returned object, this does not make a copy and saves whatever effort would have been consumed by making a copy.
Returning a reference to a local is something that can be difficult or impossible for the compiler to detect. For example:
int & f()
{
int x;
extern int & g(int & x);
// Does this return a reference to "x"?
// The compiler has no way to tell.
return g(x);
}
Even without calling external functions, it can still be difficult to analyse a complex program flow to tell whether the returned reference is to a local; rather than trying to define what counts as "simple enough" to diagnose, the standard doesn't require a diagnostic - it just states that it gives undefined behaviour. A good compiler should give a warning, at least in simple cases.
Binding a temporary to a non-const reference is something that the compiler can easily detect, and so the standard does require a diagnostic for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With