Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question regarding return functions in C

Tags:

c

struct

I am a java programmer learning C. Have a question regaring functions. What are the differences between this:

main()
{
    struct person myperson;

    myperson = myfunction();

    return;
}

struct person myfunction()
{
     struct person myPerson;
     myPerson.firstname = "John";
     myPerson.lastname = "Doe";
     return myPerson;
}

VS

main()
{
    struct person *myperson;

    myperson = myfunction();

    return;
}

struct person* myfunction()
{
     struct person *myPerson;
     myPerson = malloc(sizeof(struct person));
     myPerson->firstname = "John";
     myPerson->lastname = "Doe";
     return myPerson;
}

Are these legal in C? And y would 1 choose one over the other. Thanks so much guys!

like image 807
JasonKeef Avatar asked Sep 07 '11 13:09

JasonKeef


People also ask

What happens when a function returns in C?

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.

Can C function return multiple values?

In C or C++, we cannot return multiple values from a function directly.

Which function must not use a return statement?

The void functions are called void because they do not return anything. “A void function cannot return anything” this statement is not always true. From a void function, we cannot return any values, but we can return something other than values.

What is the purpose of returning value from function?

A return is a value that a function returns to the calling script or function when it completes its task. A return value can be any one of the four variable types: handle, integer, object, or string.


1 Answers

first code sample:
you create a struct in myfunction() on your stack and return it. then, you create another stack struct, and you copy the first to the second. the first is destroyed. the second will be automatically destroyed when you are out of the scope.
2 structs were actually created.

second code sample:
you create a struct in myfunction(), and then you copy only the address. the struct in main will actually be the same struct.
only one struct is created in here.

both code samples work, but for the later you will have to explicitly free the memory allocated for the struct, to avoid memory leak, but performance should be better since you don't need to copy the struct!

EDIT:
as mentioned by @Mat: this of course neglects the overhead of malloc(), which is not true for small structs.

like image 95
amit Avatar answered Sep 19 '22 17:09

amit