3

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;
{
}
1
  • Not sure, what you are trying to achieve in first example but Second is K&R and format of function definition, it is not approved by C standard. Commented Sep 2, 2012 at 7:21

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! And i can't use this in any C++ standard, yes?
@NikitaTrophimov: You can certainly return structs in C++, too, but you can't define them in the function declaration.
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.