Returning a pointer

c++, pointers

Solution

It doesn't work. It is undefined behaviour. It may seem to work, because "correct behaviour" is a subset of "any possible behaviour".

Problem

I don't understand how this example can possibly work: ``` double * GetSalary() { double salary = 26.48; return &salary; } main() { cout << *GetSalary(); //prints 26.48 } ``` `salary` is a local variable in `GetSalary()`, thus after returning from the function, this cell might possibly be overwritten by another function. I don't see how returning a pointer to a local variable (not instanciated on the heap) can ever possibly work.

Original source

Related problems