Utkarsh Pandey
Utkarsh Pandey

Reputation: 51

Function returning a value

I am doing a course on data structure and algorithm. There is this code written here where there is a function mf(). It returns int old.My question is that how can it return old since int old is a local variable which will be destroyed at the time of return.

class x{
public;
int m;
int mf(int v){int old = m; m = v; return old; }
};

Upvotes: 0

Views: 146

Answers (2)

bigeast
bigeast

Reputation: 637

C/C++ will pass the value of the return variable to a temporary value:

class x{
    public:
    int m;
    int mf(int v){
        int old = m; // store member var m in old.
        m = v; // change m to v.
        return old; // return the old value of m.
                    // **tmp = old;**
    }
};

x foo;
foo.m = 5;
int n = foo.mf(3); // n = tmp; so now tmp is 5, and it's assigned to n;

You can observe the copy from old to tmp and destory of old and tmp when you return a class and print a message in the constructor and destructor.

FYI, the compiler can use return value optimization (RVO) to store the return value directly in n.

Upvotes: 0

gmiley
gmiley

Reputation: 6604

The function returns the value of old, not the variable itself. It is returning a copy of the value.

Upvotes: 3

Related Questions