Search code examples
cstructurereturn-value

which is better way to returning structure from function?


there are various ways to return structure from function like return whole structure or return the pointer only. returning pointer is useful to avoid stack overhead as we don't needed to return whole structure. In other side for small structure it is good to go with returning whole structure.

In my case i have below scenario to get structure from another file and thought various methods to use but as i am new to C so still i needed some expert advise like

which method is better? Any issue in it? or any suggestion for new method?

returning large structure as whole cause any stack issue?

file1.c

static struct_type mysruct; //Note : here struct size is 250+ bytes

//Method 1
struct_type getStructDataMethod1()
{
    return mysruct;
}

//Method 2
void getStructDataMethod2(struct_type *structPtr)
{
    if(structPtr != NULL)
    {
        memcpy(structPtr, &mysruct, sizeof(struct_type));
    }
}
//Method 3
void getStructDataMethod3(struct_type *structPtr)
{
    *structPtr = mysruct;
}

file2.c

void myFunction()
{
    struct_type mylocalStruct1 = getStructDataMethod1();
    struct_type mylocalStruct2;
    struct_type mylocalStruct3;

    getStructDataMethod2(&mylocalStruct2);
    getStructDataMethod3(&mylocalStruct3);

}

Solution

  • The rule of thumb is to always pass structs to function by pointers and never by value, for the reasons you mention yourself. You should only make special case exceptions to this rule in case a struct is very small.

    So either method 2 or 3 is the correct way to do it. Apart from the NULL pointer check, they are equivalent.


    Minor issue not related to your question: never write functions as void myFunction() in C, this is obsolete style. Use void myFunction(void) instead.