Look at the code below. I know it doesn't return the address of local variable, but why does it still work and assign the variable i
in main() to '6'? How does it only return the value if the variable was removed from stack memory?
#include <iostream> int& foo() { int i = 6; std::cout << &i << std::endl; //Prints the address of i before return return i; } int main() { int i = foo(); std::cout << i << std::endl; //Prints the value std::cout << &i << std::endl; //Prints the address of i after return }
Objects returned by reference must live beyond the scope of the function returning the reference, or a dangling reference will result. Never return a local variable by reference.
The return statement should not return a pointer that has the address of a local variable ( sum ) because, as soon as the function exits, all local variables are destroyed and your pointer will be pointing to someplace in the memory that you no longer own.
Returning values by reference in C++ A C++ function can return a reference in a similar way as it returns a pointer. When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var.
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).
You got lucky. Returning from the function doesn't immediately wipe the stack frame you just exited.
BTW, how did you confirm that you got a 6 back? The expression std::cout << &i ...
prints the address of i
, not its value.
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