Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing return value of a function as reference

What is supposed to happen in the following case:

int functionA() {
    return 25;
}

void functionB(const int& ref) {
    cout << ref << endl;
}

void start() {
    functionB(functionA());
}

When compiling this example, it outputs the correct value 25. How does this work? Should'nt the referenced return value on the stack be deleted (removed from the stack) when using only a reference to it, or is the behaviour undefined?

like image 269
maxdev Avatar asked Sep 16 '13 14:09

maxdev


People also ask

How can you pass value by reference in function?

To pass a value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.

How do you return a reference by passing it?

Example: Return by Reference In program above, the return type of function test() is int& . Hence, this function returns a reference of the variable num . The return statement is return num; . Unlike return by value, this statement doesn't return value of num , instead it returns the variable itself (address).

Can a function return a reference?

Functions can be declared to return a reference type. There are two reasons to make such a declaration: The information being returned is a large enough object that returning a reference is more efficient than returning a copy. The type of the function must be an l-value.

Can you pass by reference?

When a function is called, the arguments in a function can be passed by value or passed by reference. Callee is a function called by another and the caller is a function that calls another function (the callee). The values that are passed in the function call are called the actual parameters.


2 Answers

This "works" because of const int& ref - when a reference is const (guarantees that you don't want to change it), the compiler will produce a temporary object in the calling code (start in your case), and then pass the reference to that.

If you remove const it will fail to compile because functionA's result can't be turned into a reference.

like image 97
Mats Petersson Avatar answered Oct 25 '22 15:10

Mats Petersson


There is no "return value on the stack" (let alone a "stack"): functionA returns an int by value, so the expression functionA() is simply a temporary value of type int. This value binds to the constant reference in functionB, and since its lifetime is that of the full expression, everything is fine.

like image 26
Kerrek SB Avatar answered Oct 25 '22 13:10

Kerrek SB