user1279988
user1279988

Reputation: 763

Unable to understand the return type of the code snippet

I am puzzled why this one is right. The return value is reference type int&, but the the h() function return a value int type in sentence return x. So, how does the int return change to a int &?

This is the code snippet and compiles fine with the C++ compiler.

int& h() {
 int q;
 static int x;
 return x;
}

Upvotes: 0

Views: 115

Answers (3)

bames53
bames53

Reputation: 88155

int& is a reference to an int. x is an int. Therefore return x; from a function that returns an int& returns a reference to x.

Also:

Returning a reference to a local variable is dangerous, because local variables are destroyed when the function exits. By the time you get the reference the thing that it references doesn't exist. This is called a dangling reference and it's like a pointer that doesn't point to anything.

Static variables are not local variables and do not get destroyed when the function exits. Therefore the reference still points to a valid object when you get it.

Upvotes: 1

Component 10
Component 10

Reputation: 10497

The reference means that you're actually returning effectively the same variable so changing the value of what was returned will directly alter the value of x If the code had been writtten:

int h()
{
    int q;
    static int x;
    return x;
}

(i.e. not be reference) then you'd be returning a copy of the value of x (although you should to be fair check out Return Value Optimization.) Returning a reference is efficient, however, there are times (multi-threading being an obvious example) where it can be undesirable and confusing.

Upvotes: 1

pmr
pmr

Reputation: 59811

This returns a reference to a static int. The x is initialized the first time the function h is called. Use it like this:

int& href = h();
++href; // increments the static variable
int& href2 = h(); // another reference to the same static variable

The variable q should have no effect and I would consider it dubious.

Upvotes: 4

Related Questions