0

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;
}
  • It is **always** wrong to return a reference to a function local object. This includes non-reference function parameters. – NathanOliver Jan 18 '21 at 15:44
  • returning a reference to a local variable is wrong and that is what you are doing in both cases. Doing something wrong can yield a correct looking result sometimes, thats no surprise in general, but in C++ it can be difficult, because undefined behavior is just undefined – 463035818_is_not_an_ai Jan 18 '21 at 15:44
  • Both examples have the same problem. Even if the second example looks like it works, this is a coincidence. It could start behaving differently at any time for no apparent reason. – François Andrieux Jan 18 '21 at 15:44
  • Both versions of the code is undefined behavior, and both versions are broken. However, undefined behavior does not guarantee an immediate crash. Undefined behavior means anything can happen, including the program apparently working today, but tomorrow your computer will catch fire and explode in a ball of fire. If you don't want the possibility of your computer catching fire and exploding, avoid undefined behavior even if it seems to work. – Sam Varshavchik Jan 18 '21 at 15:45

0 Answers0