Josh Morrison
Josh Morrison

Reputation: 7636

What does it mean when a function signature has "&" before the name?

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. Still wrong? or just a warning issue? –

Upvotes: 2

Views: 1503

Answers (7)

Nick
Nick

Reputation: 669

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.

Upvotes: 1

Jonathan Wood
Jonathan Wood

Reputation: 67175

& 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.

Upvotes: 0

Edward Strange
Edward Strange

Reputation: 40849

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.

Upvotes: 3

Sonny Saluja
Sonny Saluja

Reputation: 7287

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.

Upvotes: 2

chrisaycock
chrisaycock

Reputation: 37930

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.

Upvotes: 4

Mark Ransom
Mark Ransom

Reputation: 308111

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.

Upvotes: 13

MerickOWA
MerickOWA

Reputation: 7592

No you cannot return a reference to a local variable.

Upvotes: 3

Related Questions