int &sum(int numa, int numb)
{
int sum = 0;
sum = suma+sumb;
return sum;
}
Is this function correct? Why does it use &
?
ADDED COMMENT: thank you all. But after I compiled it using gcc, it came up one warning but no error. It can run perfectly. St开发者_运维问答ill wrong? or just a warning issue? –
The &
means you're returning a reference. In your case, you're returning a reference to an int
, one that disappears as soon as the function returns; this is a serious bug.
This function tries to return a reference to an integer. Since the integer is local to the function, this definition is not valid; the integer will go out of scope once the function returns.
No you cannot return a reference to a local variable.
In addition to returning a reference to a local variable, which is evil incarnate, unless suma
and sumb
are declared at the global scope, the function is using names that don't exist.
Look up C++ References. It is not safe to return references (or pointers) to local variables. The local variable will be destroyed after the function exits and your returned pointer will point to undefined memory.
Since most of the above answers have cleared up the idea of a returned reference, I thought I would be a bit more precise with respect to the idea of it being "deallocated".
Functions calls place their arguments and automatic (locally declared) variables on the stack in memory. When a function returns, that memory is not zeroed out. The values are left alone, and that memory is reused for later functions as the stack grows.
So when you use this returned reference, it could be valid for a little bit, but then random data meant for other functions will write to the same spot, presenting you with garbage data.
& indicates that a reference to a variable is returned. This can help in cases where the original is a larger object because it saves having to make a copy of it in some cases.
However, I see no reason to do this for an int. In fact, since the original is deallocated when the function returns, it causes problems as you've used it here.
精彩评论