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?
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.
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).
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.
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.
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.
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.
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