简体   繁体   English

C中没有名称的函数指针

[英]Function pointer without a name in C

A normal function pointer would look like this:一个普通的函数指针看起来像这样:

void (*fun_ptr)(void);

However, I have seen this syntax used to cast something to a void function pointer:但是,我已经看到这种语法用于将某些内容转换为 void 函数指针:

(void (*)(void *))

As you can see it has no name and only has (*) in place of a name.如您所见,它没有名称,只有(*)代替名称。 What does this mean?这是什么意思? Is it only used for casting?仅用于铸造吗?

The syntax (void (*)(void *)) is a cast.语法(void (*)(void *))是一个强制转换。

the destination type of the cast is a function pointer that takes a single parameter of type void * and returns void .转换的目标类型是一个函数指针,它接受一个void *类型的参数并返回void An example of a function whose type matches this cast is:类型与此强制转换匹配的函数的示例是:

void abc(void *param);

void (*)(void *) is a type. void (*)(void *)是一种类型。 It's conceptually similar to int * .它在概念上类似于int * That doesn't have an identifier associated with it, either.它也没有与之关联的标识符。 void (*foo)(void *) is a declaration of a variable foo with that type. void (*foo)(void *)是具有该类型的变量foo的声明。

A cast expression is of the form (<type>)<expr> .强制转换表达式的形式为(<type>)<expr> So, (void (*)(void *)) can be a cast operator.因此, (void (*)(void *))可以是强制转换运算符。

However, this form is not limited to cast expressions.但是,这种形式不限于强制转换表达式。 It can be used wherever a type can.它可以在任何类型可以使用的地方使用。 For example, as the type of an argument in a function prototype:例如,作为函数原型中的参数类型:

void bar(void (*)(void *));

That declares a function bar which takes a function pointer as an argument.这声明了一个函数bar ,它将函数指针作为参数。

In C, what the standard calls a "type-name" (the type in a cast, or the argument of sizeof) has exactly the same form as a declaration of a variable of that type, just without the variable.在 C 中,标准所称的“类型名称”(类型转换中的类型,或 sizeof 的参数)与该类型变量的声明具有完全相同的形式,只是没有变量。 And the declaration of a variable reflects its use.变量的声明反映了它的用途。 In your case a pointer to a function receiving a void pointer and returning void is used like在您的情况下,使用指向接收 void 指针并返回 void 的函数的指针,例如

(*f)(p) , (*f)(p) ,

so that its declaration is所以它的声明是

void (*f)(void *P) , void (*f)(void *P) ,

(note the nested type declaration for p !), and the corresponding cast is (注意p的嵌套类型声明!),相应的转换是

(void (*)(void *)) . (void (*)(void *))

This is a simple, powerful and logical principle;这是一个简单、强大且合乎逻辑的原则; but one consequence is that for complex types the variable name appears in the middle of the declaration, as it would in the corresponding expression.但一个结果是,对于复杂类型,变量名出现在声明的中间,就像在相应的表达式中一样。

Interestingly, there is exactly one place for a variable name in a type-name (applied recursively for nested types like in your function);有趣的是,类型名中只有一个变量名的位置(递归地应用于函数中的嵌套类型); type-names are unambiguous.类型名称是明确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM