Disclaimer: I've read countless other articles on this topic and I still don't get them. Example: why do this:
void func(int a, void (*callback)(int))
{
/* do something with a and callback */
callback(3);
}
void pointme(int b)
{
/* do something with b */
}
int main()
{
void (*pf)(int);
pf = &pointme;
func(10, pf);
}
when I can simply do this:
void func(int a)
{
pointme(3);
/* do something with a*/
}
void pointme(int b)
{
/* do something with b */
}
int main()
{
func(10);
}
??? I really don't get it. Any help would be super-appreciated. Thanks!!!
when I can simply do this [...]
That's correct, you should call the function directly if you can. However, there are situations when you cannot make a direct call, because the function that you are trying to call does not exist in your code. Of course, the function will be there in the finished program, but in many situations you would develop a library that interacts with other people's code, and needs to compile by itself.
In addition, there are situations when you can call the function directly, but you do not want to do it to avoid code repetition.
This is when function pointers come in handy: the caller can tell your function which of his functions to call.
Consider designing a threading library that lets users run their functions in parallel. This library cannot make direct references to user code, for two reasons:
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