Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function returning struct in C

Tags:

c

struct

Where can we write code like

struct Foo
{
    int bar;
    int baz;
} foo()
{

}

C89/C90? C99? C11? Or maybe it's K&R only?

And what about this

void foo(bar, baz)
int bar;
int baz;
{
}
like image 243
FrozenHeart Avatar asked Dec 03 '25 13:12

FrozenHeart


2 Answers

It's standard since C89. In K&R C, it was not possible to return structs, only pointers to structs.

It is possible and useful, certainly since C89, to return a struct.

Your second example foo is old K&R C and is deprecated in newer standards.

Notice that on Linux x86-64 the ABI defines calling conventions which returns a two membered structure directly thru registers. Other structures are returned thru memory, so may be a little slower to return than a single pointer.

For instance, you could define a point to be a struct of two numbers (e.g. int or double) called x and y and return such a struct from some getPosition routine. On Linux/x86-64, the two numbers would be returned in two registers (without bothering building some struct in memory, when optimization is enabled and possible), e.g.:

 struct point_st { int x, y; };

 struct point_st getPosition(void);

 struct point_st getPosition () {
   struct point_st res = {-1,-1};
   res.x = input_x();
   res.y = input_y();
   return res;
 };

You generally want to declare the returned struct before the function's prototype.

like image 31
Basile Starynkevitch Avatar answered Dec 06 '25 02:12

Basile Starynkevitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!