vendredi 3 janvier 2020

Scope of variable returned by referance

In the follwing code, a string str is created in fun() and as fun() ends, the variable goes out of scope. So, the reference to it should be invalid and throw some errors or garbage value. But this program runs fine. Why? i expected some error as the referance to a local variable of fun() was returned but the code runs fine.

#include <iostream> 
using namespace std; 
string& fun(){
    string str="ag";
    string &q=str;
    cout<<q<<" "<<&q<<endl;
    return q;
}
int main(){
    string &s=fun();
    cout<<s<<" "<<&s<<endl;
    return 0;

}

Aucun commentaire:

Enregistrer un commentaire