Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a function to be used as a function pointer in c?

Tags:

c

I am confused with function pointer declaration.

I have an api abc() which takes an argument as so:

void abc(void (*my_func)(void *p), int, int)

If I want to pass my function as an argument to that api, I am declaring it in my .h file:

void (*xyz)(void *p)

and defining as:

void *(xyz)(void *p){
statements;
}

but this throws an error. Please correct me.

like image 534
coolcracker Avatar asked May 09 '26 15:05

coolcracker


2 Answers

you just need to declare it:

void xyz(void *p);

with the implementation the same way.

When you pass it into your api, the type system figures out it out automatically:

abc(xyz,someint,anotherint);
like image 186
Nate Avatar answered May 11 '26 06:05

Nate


The (*xyz) means that it is a function pointer.

Function pointers are best handled with typedefs. So it is guaranteed that there is nothing wrong.

I would do the following:

// define a type for the function (not its pointers, as you can often read)
typedef void my_func_t(void *p);

void abc(my_func_t*, int, int);

// declaration in order to be type-safe - impossible if only the pointer would be typedef'd
my_func_t my_func_impl; 

// definition:
void my_func_impl(void *p)
{
    do_something_with(p);
}

and then you can call your abc() with abc(my_func_impl, 47, 11). You can put a & before my_func_impl there in order to point out that it is the function address you wish to obtain, but it is optional.

An alternative would be to write

typedef void (*my_func_p)(void *p);

and use my_func_p instead of my_func_t *, but this has the disadvantage that you cannot write my_func_t my_func_impl;.

Why would you want to do that?

Well, if, by any coincidence or accident, the function definition or the typedef is changed, they won't match any longer, but the collision is not declared as error, but only as warning (Mismatch pointer). OTOH, my_func_t my_func_impl; serves as a kind of prototype, which causes a function header mismatch, which is an error.

like image 36
glglgl Avatar answered May 11 '26 05:05

glglgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!