How does C return a structure? [duplicate]

In my experience, there is no standard way how C returns a structure. To be able to pass a struct, the compiler usually (invisibly to the user) passes a pointer to the struct, to which the function can copy the contents. How this pointer is passed (first or last on stack) is implementation dependent. Some compilers, like 32 bit MSVC++ return small structures in registers like EAX and EDX. Apparently, GCC returns such a struct in RAX, in 64 bit mode.

But, once again, there is no standard way how this is done. That is no problem when the rest of the code using a function is also compiled by the same compiler, but it is a problem if the function is an exported function of a DLL or a lib. I have been bitten by this a few times, when using such functions from a different language (Delphi) or from C with a different compiler. See this link too.

Leave a Comment