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!
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.
In C or C++, we cannot return multiple values from a function directly.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With