简体   繁体   中英

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 *))

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.

the destination type of the cast is a function pointer that takes a single parameter of type void * and returns void . An example of a function whose type matches this cast is:

void abc(void *param);

void (*)(void *) is a type. It's conceptually similar to int * . That doesn't have an identifier associated with it, either. void (*foo)(void *) is a declaration of a variable foo with that type.

A cast expression is of the form (<type>)<expr> . So, (void (*)(void *)) can be a cast operator.

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.

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. 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

(*f)(p) ,

so that its declaration is

void (*f)(void *P) ,

(note the nested type declaration for p !), and the corresponding cast is

(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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