Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are returned values stored?

Tags:

c++

c

I know that coding with C, the return value of a function return to caller using %eax register.

With c++ it is also possible to return structs and not just 'Primitive' types, so when a function returns a struct, where is the returned value stored (stack, heap, etc)?

Example Code:

class Student
{
private:
    int m_id;
public:
    Student(int id)
    {
        m_id = id;
    };
    ~Student();
    int getId()
    {
        return m_id;
    };
};

Student myFunc()
{
    return Student(123);
}

int main()
{
    //How does 'student1' get the value from the function?
    //Does 'myFunc' write directly to the stack of main?
    Student student1 = myFunc();


    return 0;
}
like image 973
iso532 Avatar asked May 30 '18 09:05

iso532


People also ask

Where is the return value stored in Java?

The return value can be stored inside a variable at the method's call site.

What happens when a value is returned?

Nothing. The return value is simply discarded.

Where does the return statement and its value return?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.

Where does a function return to?

A return is a value that a function returns to the calling script or function when it completes its task.


1 Answers

In C this depends on the ABI of the platform.

On x86_64 linux, there are several classes of data types but in simple terms, small simple structs (~ <= 2 longs) are returned in registers and large ones through the stack.

The latest C++ should guarantee RVO (Return Value Optimization) I believe, which means structs/classes should get allocated on the stack in the caller and the callee should "secretly" write to them via a pointer (C ABIs/compilers can do this too, but in C++, RVO additionally avoids destruction and copy-construction).

You can always look at the assembly or write a benchmark to verify the passing convention.

(In my opinion, it is, however, best to limit oneself to simple return types in C so you don't have to worry. (Original C didn't even allow one to return structs.) In C++ with RVO it shouldn't matter.)

like image 61
PSkocik Avatar answered Sep 22 '22 01:09

PSkocik