0

Possible Duplicate:
C++ Returning reference to local variable

I am not able to pass the reference properly in the following code.

myint& myint::abs()
{
  myint i=*this;
  myint &t=i;
  t.setsign(0);
  return t;      
}

The reference 't' is correctly modified in the abs() function. I have printed it and found that its correct. However the value received in main() is always wrong.

I have used the following statement in main()

myint a("-12"); /*gives a=-12 with each digit in a linked list node. separate data field for sign.*/
myint b=a.abs();

b received is 0, the default value.

Thanks in advance.

Community
  • 1
  • 1
RijulB
  • 565
  • 1
  • 4
  • 10
  • 1
    [Returning reference to a local variable](http://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable). – DCoder Oct 06 '12 at 15:13
  • Welcome to Stack Overflow. This is a nicely written question (thank you), but it is one that has been asked before with only the most trivial differences. As such, it is likely to be closed shortly. You can see a number of good answers to your question already by following the link given by @DCoder. – Jonathan Leffler Oct 06 '12 at 15:20
  • Re: "The reference 't' is correctly modified" -- the code does not modify the reference `t`. It modifies the `int` that `t` is a reference to. References can not be modified (absent perversion). – Pete Becker Oct 06 '12 at 15:44
  • Hi DCoder, Thanks for the reply. I had seen this question but didnt think it was useful. However, having gone through it again, I think I know what I am missing. Thanks again. – RijulB Oct 07 '12 at 09:57

1 Answers1

1

You are returning a reference to a local variable 'i'. i has gone out of scope when you return from the function so using the reference to it causes undefined behavior.

jcoder
  • 29,554
  • 19
  • 87
  • 130