-1

please look at this code firstly . I run it on g++ complier. I want to know how it will act when the function "add" return a reference to local variable , but it run correctly, no crash . Why ?

int & add (int a,int b) {
   int c = a + b ;
   return c ; 
}
int main()
{
   cout<<add(1,2)<<endl;
   int a = add(1,2);
   cout<<a<<endl;
}
GuangshengZuo
  • 4,447
  • 21
  • 27
  • It is undefined behavior. Most of the times for smaller programs like this it works but when u take complex programs using heavy memory and recursive etc it is undefined behavior. – Sagar Sakre Aug 16 '14 at 12:44

2 Answers2

3

Do not return a reference to a local variable.

It may or may not work.

But will sometime down the line it will bite you.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
3

Because it is undefined behavior. You can't rely on it working and as your code grows it won't.

Gerald
  • 23,011
  • 10
  • 73
  • 102