Jokaaa
Jokaaa

Reputation: 37

Returning a variable about to be destroyed in a function

j is destroyed when the function calls return

k is destroyed at the end of the enclosing brackets

If i pass in 9 for j, k is created and will be assigned 81

Returning k will set func1 which is a reference to an integer = k

Returning will immediately terminate the function

My question is, are k and j terminated at the return statement?

If they are func1 should reference nothing...

But i have tried to run this code and it works...

int& func1(int j){
 int k = j*j;
 return(k);
}

Upvotes: 0

Views: 73

Answers (2)

Hatted Rooster
Hatted Rooster

Reputation: 36483

and it works...

No, it appears to work. The moment you try to access the reference returned by func1 you enter the Undefined Behavior realm. At that point all bets are off, it could've printed out 42, printed out nothing, crash, eat your CMOS battery etc.

Upvotes: 1

Stack Danny
Stack Danny

Reputation: 8126

If they are func1 should reference nothing...

You are correct. Try using the reference some more time and you will see:

#include <iostream>

int& func1(int j) {
    int k = j * j;
    return(k);
}

int main() {
    int& addr = func1(9);

    for (int i = 0; i < 10; ++i) {
        std::cout << addr << '\n';
    }
}

Output:

81
2758456
2758456
2758456
2758456
2758456
2758456
2758456
2758456
2758456

Upvotes: 0

Related Questions