我最近在 C 程序中遇到了一个奇怪的语法。
struct connector_agent_api{
bool (*receive)(slot *s, uint8_t *data, uint8_t length);
}
“接收”是一个函数指针吗?
如果它是一个函数指针,为什么它有命名参数?是不是应该像下面这样?
bool (*receive)(slot *, uint8_t *, uint8_t);
它肯定会编译并在库中使用。我在互联网上搜索了很多,并试图证明这种语法的合理性。我仍然不知道为什么这个东西可以编译... :(
最佳答案
函数指针中的参数名称是可选的,就像函数声明中的参数名称是可选的一样。这是因为未使用给定的参数名称,因此两种格式都是允许的。
在 C standard 的第 6.7.6.3 节中关于函数声明符,它包括函数原型(prototype)和函数指针,第 6 段指出:
A parameter type list specifies the types of, and may declare identifiers for, the parameters of the function.
函数参数需要名称的唯一地方是函数的实际定义。
对于函数定义,第 6.9.1p5 节指出:
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.
关于c - 具有命名参数的函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55871507/