Returning local reference from a function

Hi all
Im new to c++ and Im trying to figure somthing out for a few hours now.

I dont get why the following piece of code works

int & func()
{
int x = 5;
int & a = x;
return a;
}

and when I cout << func() i get 5 in the console window

after all x is a local variable and itt not define after func returns.

The following does not compile

int & func()
{
int x = 5;
return x;
}

I dont understand the difference between the 2 function

please help me :)

Thank u in advance
Last edited on
The first function doesn't return anything so the program has undefined behaviour and anything could happen.

Are you sure the second function gives you an error and not a warning? The problem with that function is that it returns a reference to a variable that is local in the function. When the function ends x will no longer exist so you end up returning a reference to a variable that does not exist. Trying to use that value gives undefined behaviour.
thank u for ur reply

I typed the first function without any return statement...I fixed it now thank u.
I still dont understand why when returning a reference the variable the function return stores number 5?
after all x is destroyed when the function end. Like ur argument for the second function in my original post...

Thank u in advance
Let consider at first the second code.

1
2
3
4
5
int & func()
 {
 int x = 5;
 return x;
 }


Here a local variable created with the return statement is bounded to non-const reference. Such a program is ill-formed. So the compiler issue a diagnostic message.


Now consider the first example

1
2
3
4
5
6
7
int & func()
 {
 int x = 5;
 int & a = x;
 return a;
 }
 


In this example a local variable is not created while the return statement is executed. You are returninig a reference. So compiler does not issue an error though this code is also ill-formed.
As for me in this example the compiler also shall issue a diagnostic message. This is determined by the quality of the compiler.


Last edited on
I see

Thank u:-)
Topic archived. No new replies allowed.