Code 1:
#include<iostream>
using namespace std;
int& func()
{
int a=6;
return a;
}
int main(void)
{
int a = func();
cout<<a;
cin.get();
return 0;
}
According to my thought , first of all func() will create a temporary reference to a (as it is returning by reference) , and then through that temporary reference it will provide value to a.
Please correct me if I'm wrong!
Code 2:
#include<iostream>
using namespace std;
int& func()
{
int a=6;
return a;
}
int main(void)
{
int& a = func();
cout<<a;
cin.get();
return 0;
}
I think this time too func will create a temporary and assign value to a as a reference.But after function is returned shouldn't func value be trashed ?
How 'a' in main is still printing correct values ?
Please somebody explain.
Regards!