ZR_xdhp
ZR_xdhp

Reputation: 361

Function pointer with named arguments?

I recently came across a strange syntax in C program.

struct connector_agent_api{
    bool (*receive)(slot *s, uint8_t *data, uint8_t length);
}

Is "receive" a function pointer?

If it is a function pointer, why does it have named arguments? Should it be like the following one?

bool (*receive)(slot *, uint8_t *, uint8_t);

It certainly compiled and being used in a library. I searched on internet a lot and tried to justify this kind of syntax. I still don't know why this thing can be compiled... :(

Upvotes: 18

Views: 2308

Answers (2)

dbush
dbush

Reputation: 223719

The names of arguments in a function pointer are optional, just as the names of arguments in a function declaration are optional. This is because parameter names if given are not used, so both formats are allowed.

In section 6.7.6.3 of the C standard regarding Function Declarators, which includes both function prototypes and function pointers, paragraph 6 states:

A parameter type list specifies the types of, and may declare identifiers for, the parameters of the function.

The only place where function parameters require a name is in the actual definition of a function.

For a function definition, Section 6.9.1p5 states:

If the declarator includes a parameter type list, the declaration of each parameter shall include an identifier, except for the special case of a parameter list consisting of a single parameter of type void , in which case there shall not be an identifier. No declaration list shall follow.

Upvotes: 20

machine_1
machine_1

Reputation: 4454

What makes you think it is a strange syntax? It is a valid declaration as per C standard. The fact that the parameters are named is irrelevant. The naming of such parameters is optional in this case. It can be really helpful if you or someone else is using an IDE because it could display the complete prototype upon using the function pointer to call the function and thus give a hint to the coder about the arguments to be supplied.

Upvotes: 5

Related Questions