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;
{
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With