I have the following functions (wrote in Visual C++ 2005)
int &getInt_1()
{
int a = 5;
int &p = a;
int p1 = p; // Line 1
return p1;
}
int &getInt_2()
{
int a = 5;
int &p = a;
return p;
}
As I have known so far, both the above functions return address of local variable. If I am right, then I have some questions as follows:
-
What are the differences between above functions? Why
getInt_1()gets warning from the compiler ("returning address of local variable") whilegetInt_2()does not? -
What does
Line 1mean? AfterLine 1, doesp1become a reference toaas well?
getInt_1returns a reference to p1.getInt_2returns a reference to a. Both are the same undefined behavior, don’t do it. VC should give a warning on both.