3

Possible Duplicate:
Can a local variable's memory be accessed outside its scope?!

Here is a code:

    #include <iostream>
using namespace std;

double &GetSomeData()
{
double h = 46.50;
double &hRef = h;
return hRef;
}

int main()
{
double nonRef = GetSomeData();
double &ref = GetSomeData();
cout << "nonRef: " << nonRef << endl;
cout << "ref: " << ref << endl;
return 0;
}

the nonRef is printed OK as 46.5 the ref is not OK.

is the first output behavior is correct or just got lucky?

Thanks

Community
  • 1
  • 1
sramij
  • 4,775
  • 5
  • 33
  • 55
  • 5
    This has been asked before (more than once). [Accepted answer](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794) received 1642 upvotes (to date)... – Eran Jul 14 '11 at 06:19
  • Eric Lippert makes perfect analogies. Coincidentally I didn't read the first comment on his answer until just now :) – Marlon Jul 14 '11 at 06:46

3 Answers3

10

Yes you got lucky.

Returning reference to local variable is Undefined Behavior. Undefined Behavior means anything can happen and a behavior cannot be defined.

Regarding Undefined Behavior,

C++ Standard section 1.3.24 states:

Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

Normally you use * to declare a pointer variable and also to dereference the pointer back to the original variable afterwords. & returns the address from a variable

I haven't tested this, but does the following work any better?

#include <iostream>
using namespace std;

double* GetSomeData()
{
  double h = 46.50;
  return &h;
}

int main()
{
  double nonRef = GetSomeData();
  double* ref = GetSomeData();
  cout << "nonRef: " << nonRef << endl;
  cout << "ref: " << *ref << endl;
  return 0;
}
Devin Garner
  • 1,361
  • 9
  • 20
  • 1
    You're missing the point. Whether you use references or pointers is irrelevant in this case. – Fiktik Jul 14 '11 at 06:09
  • 1
    Returning address to local variable is Undefined Behavior. Undefined Behavior means anything can happen and a behavior cannot be defined. – Jaffa Jul 14 '11 at 06:10
0

If you are merely testing the difference between these two lines:

double nonRef = GetSomeData();
double &ref = GetSomeData();

Try classes.

class test
{
public:
    int x;
    int& getx()
    {
        return x;
    }
};

//Some code
test c;
int nonRef = c.getx();
int &ref = c.getx();

ref = 8;
nonref = c.getx();

After this, c.getx() returns 8.

holgac
  • 1,509
  • 1
  • 13
  • 25