How do I call a function that takes an anonymous struct in C?
Such as this function
void func(struct { int x; } p)
{
printf("%i\n", p.x);
}
When a function declaration that provides a prototype is in scope, the arguments to calls to that function must be have types compatible with those declared in the prototype, where "compatible" has a specific meaning defined by the standard:
Two types have compatible type if their types are the same. Additional rules for determining whether two types are compatible are [not relevant to the case in question]. Moreover, two structure, union, or enumerated types declared in separate translation units are compatible if their tags and members satisfy the following requirements: If one is declared with a tag, the other shall be declared with the same tag. If both are completed anywhere within their respective translation units, then the following additional requirements apply: there shall be a one-to-one correspondence between their members such that each pair of corresponding members are declared with compatible types; [...] and if one member of the pair is declared with a name, the other is declared with the same name. For two structures, corresponding members shall be declared in the same order. [...]
(C11, 6.2.7/1)
Being "the same type" in the sense meant by the standard is a matter of scope, and there is no way for a caller of your function to satisfy that because the scope of the structure declaration in a function parameter list is restricted to the function definition in which it appears, if any, or to the parameter list alone if it appears only in a prototype.
To call that function, then, you must somehow take advantage of the additional rules for type compatibility, which are applicable (only) if func()
is defined in a different translation unit than the caller. In that case, the easiest thing to do is probably to typdef
a compatible type in the caller's translation unit:
typedef struct { int i; } one_int;
You would then prototype the function like so in that TU:
void func(one_int p);
and you would call it with a parameter of type one_int
. For example,
one_int oi = { 1 };
func(oi);
Do note, however, that although the above prototype is compatible with the function definition given in the question as long as they appear in different translation units, the two cannot appear in the same translation unit, so you cannot follow the usual recommendation that each .c file #include
the header(s) declaring its functions.
Overall, it would be far better to lift the struct declaration out of the prototype, either with the help of a typedef
such as is demonstrated above, or by giving it a tag, either one of which provides for it to be referenced from code away from its definition.
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