Home >Backend Development >C++ >Why is Returning a Reference to a Local C Variable Generally Discouraged?
Returning a Reference to a Local Variable
In C , returning a reference to a local variable is generally discouraged as it can lead to dangling references. However, in certain circumstances, it may still appear to work, as in the example below:
int& foo() { int i = 6; std::cout << &i << std::endl; return i; } int main() { int i = foo(); std::cout << i << std::endl; std::cout << &i << std::endl; }
This code compiles and runs without errors, and it prints:
0xfefef2 6 0x7ffe82600698
Contrary to expectations, the variable i in main() still holds the value 6 after the call to foo() has returned. This is because, in this case, the compiler has extended the lifetime of the local variable past the end of the foo() function.
This behavior is implementation-specific and should not be relied upon. In general, it is considered good practice to avoid returning references to local variables. If you need to return the value of a local variable, it is preferable to return it by value instead.
The above is the detailed content of Why is Returning a Reference to a Local C Variable Generally Discouraged?. For more information, please follow other related articles on the PHP Chinese website!