1

In C component selection, what is the benefit of structure-returning function? for example:

struct S {
   int a, b;
} x;

Why is it that I can assign the above struct as a function as shown below, Is there any benefit of doing this?

extern struct S f(); /* Why is this neccesary? */
x = f(); /* Is this accurate */

Open my eyes on this guys.

Bitmap
  • 12,402
  • 16
  • 64
  • 91
  • 1
    It is not clear that you are asking here... –  May 14 '12 at 19:08
  • Here's a similar question for defining the signature of function that would like to return more than one variable. http://stackoverflow.com/a/8999520/143897 – Jay D May 14 '12 at 19:17

3 Answers3

2

It's just a function that happens to return a struct. There's nothing more to it than that. You wouldn't be surprised to see a function return an int, why be surprised when one returns a struct?

As an aside, the extern is superfluous here because that is the default storage class for functions.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
2

It is useful so that you can return multiple values from a function.

For example, you can use it like this

struct Point {
   int x;
   int y;
};

struct Point getMousePos()
{
    struct Point pos;
    pos.x = 567;
    pos.y = 343;
    return pos; 
}

int main()
{
    struct Point mouse_pos = getMousePos();
    printf("Mousepos %d,%d\n", mouse_pos.x, mouse_pos.y");   
}

The function can be forward declared with extern (this would normally be done in a header file), so that other functions know its prototype i.e. its parameters and return type, even if the function is itself defined in another file.

0

If you get a copy of a struct instead of a pointer to it, you know that you never have to worry about free()ing it, or whether there are any data races where one thread is writing to the struct while another reads from it, or whether the pointer returned by the function will be invalidated by some action that might be outside of your control.

Matt K
  • 13,370
  • 2
  • 32
  • 51