What is a dangling reference? [duplicate]

Yes it is indeed an undefined behavior because you are returning a reference to automatic variable which will be destroyed when execution of bar() completes

You can avoid it by writing:

#include <iostream>
using namespace std;

int& bar()
{
    static int n = 10;
    return n;
}

int main() {
    int& i = bar();
    cout<<i<<endl;
    return 0;
}

In this case static variable n will not be destroyed when execution of bar() completes, it will be destroyed when your program terminates.

Leave a Comment

tech