Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointer without a name in C

Tags:

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?


2 Answers

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);
like image 75
dbush Avatar answered Sep 19 '25 06:09

dbush


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.

like image 29
Ken Thomases Avatar answered Sep 19 '25 07:09

Ken Thomases