Returning a Reference to a Local Variable
The code snippet below returns a reference to a local variable, which is generally considered bad practice in C :
int& foo() { int i = 6; return i; }
This code will work as expected, assigning the value of the local variable i to i in the main function. However, this can lead to undefined behavior because the local variable's memory is freed when the function returns.
You might be wondering how this still works, since local variables are removed from stack memory upon function return. The reason is that the stack frame for the function is not always immediately wiped after returning. This means that the reference returned by foo() is still valid after the function has finished executing.
You should be aware that this behavior is not guaranteed and may vary depending on the compiler and optimization settings. Therefore, it's best to avoid returning references to local variables and instead return copies of the data if necessary.
The above is the detailed content of Why is Returning a Reference to a Local Variable in C Considered Bad Practice?. For more information, please follow other related articles on the PHP Chinese website!