Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any case for which returning a structure directly is good practice?

Tags:

c

coding-style

IMO all code that returns structure directly can be modified to return pointer to structure.

When is returning a structure directly a good practice?

like image 437
new_perl Avatar asked Dec 09 '22 05:12

new_perl


2 Answers

Modified how? Returning a pointer to a static instance of the structure within the function, thus making the function non-reentrant; or by returning a pointer to a heap allocated structure that the caller has to make sure to free and do so appropiately? I would consider returning a structure being the good practice in the general case.

like image 134
K-ballo Avatar answered Jan 05 '23 00:01

K-ballo


The biggest advantage to returning a complete structure instead of a pointer is that you don't have to mess with pointers. By avoiding the risks inherent with pointers, especially if you're allocating and freeing your own memory, both coding and debugging can be significantly simplified.

In many cases, the advantages of passing the structure directly outweigh the downsides (time/memory) of copying the entire structure to the stack. Unless you know that optimization is necessary, no reason not to take the easier path.

like image 43
goldPseudo Avatar answered Jan 05 '23 00:01

goldPseudo