Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

return a struct

Name: Anonymous 2009-12-25 13:14

Hi /prog/
I'm wondering if it's legal to return a struct like the div(3) function does. Example:

typedef struct {
  int k;
  int j;
} Guybrush;

Guybrush fubar() {
  Guybrush retval;
  retval.k = 42;
  retval.j = 37;
  return retval;
}


By compiling it with gcc I don't get any error nor warning. Besides the produced assembly code is strightforward: it just uses a location in the stack of the calling procedure as storage area for the "retval" variable.

My question is: is it a good way of programming? I feel it's a little weird. Also I know it's better to exploit pointers, but this is not always a choice.

Name: Anonymous 2009-12-25 18:06

>>1
Yep, valid ansi C. Some ancient non-compliant compilers don't support it; I believe -Wextra, or maybe some other crazy flag, will warn about a return-by-value. Ýou really don't need to worry about those.

If the struct is huge, take a pointer instead. In my own C projects, I always take a pointer for any struct bigger than int64 as a general rule of thumb; it's very slightly more work, but if you do it everywhere it gives a very consistent API and code style (and it's fast).

Also it's obviously a basic requirement of sepples, since e.g. returning a std::string is basically returning a struct by value with the addition of calling a copy constructor (move constructor in sepplesox).

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List