#returning struct vs pass pointer

1 messages ยท Page 1 of 1 (latest)

vivid wing
#

Hello ๐Ÿ‘‹ I have a general question about the following piece of code:

// Version 1: returns a structure
struct Foo get_foo(T *t) {
  return (Foo) {
    .t=t
  };
}

// Version 2: pass a pointer
void get_foo(T *t, struct Foo *result) {
  *result = (Foo) {
    .t=t
  };
}

in my understanding, the first version will require to copy the structure on the stack when returning the function, while the second actually makes the copy inside the function itself. However, both will use the stack.

Not talking about which one is more flexible in front of the question "what if the memory should be dynamically allocated" or alike, is there a clear downside of using V1 over V2, in terms of stack-management ?

wooden scaffoldBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

silver zodiac
#

Who said the struct will be passed around on the stack? Thats up to the ABI and calling convention.

Personally they're 2 cases in which i think the later might be better:

  • your struct is quite large.
  • you actually care to return a value signify an invalid struct / an error of some kind
vivid wing
silver zodiac
#

Again - thats up to the ABI. Look up 'calling convention' and see i guess?

There's nothing in the C relm dictating one way or the other

vivid wing
#

okay but, so your "if your structure is quite large", should actually be understood as "if your structure is quite large and you're using of the the ABI I have in mind", right?

silver zodiac
#

Yes. The 'large' part would depend on said ABI

vivid wing
#

and for some ABI, maybe for large structure, the converse occurs: maybe V1 is the optimal way?

#

(I mean: it's not just "large" that depends on the ABI. the entire sentence does)

silver zodiac
#

I do believe that on most (modern) architecures & OSs today the first would be passed in a register (again - believe). And forgive me here - i don't think the speed matters in these scenarios. It more of a matter of an API design. Do you want your API to avoid 'out parms'? Do you want your functions to return an error code of sort? etc

vivid wing
#

!solved