While reading this (the answer given by psychotic), I understood how to typedef and call a function pointer. But after thinking about typedefs I experimented with them a little and was able to call functions this way also:
typedef void func(unsigned char);
void test(unsigned char a);
int main()
{
unsigned char b=0U;
func *fp=&test;
while(1)
{
fp(b);
b++;
}
}
void test(unsigned char a)
{
printf("%d",a);
}
I don't get what is the the difference between using the function pointer syntax and this approach? Both seem to almost yield the same functionality.
The style
typedef void func_t (void);
...
funct_t* fp;
Is one of the clearest ways to declare function pointers. Clear because it is consistent with the rest of the pointer syntax of C.
It is equivalent to the slightly less readable
typedef void (*func_t)(void);
func_t fp;
Which in turn is equivalent to the much less readable
void (*fp)(void);
The advantage of the first style becomes obvious when you pass these as parameters to a function:
1) void sort (func_t* callback); // very clear and readable!
2) void sort (func_t callback); // hmm what is this? passing by value?
3) void sort (void(*callback)(void)); // unreadable mess
Generally, it is a bad idea to hide the pointer syntax behind typedefs. Function pointers are no exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With