I started studying C++. I didn't understand return by reference. In the following code we have a local variable i
inside the function getInt()
. The scope of i
is dependent on getInt()
. when we get out of getInt()
the variable i
will be gone. If we use the following function, we will have a segmentation fault because we are returning a reference to a variable that don't exist anymore.
int& getInt() {
int i = 10;
return i;
}
what I didn't understand is that how come when I assign i
to a reference and return that reference I managed to get the right value which is 10
. Aren't we returning a reference to a variable that will be destroyed after we exist the function?
// Online C++ compiler to run C++ program online
#include <iostream>
int& getInt() {
int i = 10;
int &x = i;
return x;
}
int main() {
int &x = getInt();
std::cout << x << std::endl;
return 0;
}