FrozenHeart
FrozenHeart

Reputation: 20736

Function returning struct in C

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;
{
}

Upvotes: 3

Views: 3634

Answers (3)

Roland Illig
Roland Illig

Reputation: 41617

In C89/C90, it is possible to have a function that returns a struct.

I didn't find any explicit definition in the standard, but a footnote in section 3.3.2.3 "Structure and Union Members" says:

EXAMPLE 1: If f is a function returning a structure or union, and x is a member of that structure or union, f().x is a valid postfix expression but is not an lvalue.

Section 3.6.6.4 "The return Statement" doesn't lose a word about structures and unions as return types though.

Section 3.5.4.3 "Function declarators (including prototypes)" says:

A function declarator shall not specify a return type that is a function type or an array type.

It does not mention any restriction on structure or union types, and since this would be the place where such a restriction would belong, they are allowed.

C99 has the same wording, it just renumbered the sections.

Upvotes: 0

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.

Upvotes: 1

user529758
user529758

Reputation:

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

Upvotes: 5

Related Questions