While it’s very handy, I very rarely, if ever, come across functions that return structs (or unions) in C, whether they are dynamically linked functions or statically defined functions.
They instead return the data through a pointer parameter.
(An dynamic example in Windows is GetSystemInfo.)
What’s the reason behind this?
Is it because of a performance issue, an ABI compatibility issue, or something else?
I would say “performance”, plus the fact that it’s even possible sometimes seems to surprise C programmers. It’s not … in the general “flavor” of C, to many, to throw around large things such as structs as if they were mere values. Which, according to the language, they really are.
Along the same lines, many C programmers seem to automatically resort to
memcpy()when the need to copy structs arises, rather than just using assignment, too.In C++ at least, there is something called “return value optimization” which is able to silently transform code like this:
into:
which does away with the (potentially stack-hungry) “true” return of a struct value. I guess even better would be this, not sure if they’re that smart:
I’m not sure if C compilers can do any of this, if they can’t then I guess that might be a real argument against struct returns, for very performance-critical programs.