Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointers - why, when I can do without?

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

like image 940
Otringal Avatar asked Dec 25 '22 08:12

Otringal


1 Answers

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:

  • Your code has no idea which functions the users are going to run concurrently, and
  • You do not want to write a separate function for each kind of function that your users may decide to pass to your library.
like image 129
Sergey Kalinichenko Avatar answered Dec 28 '22 08:12

Sergey Kalinichenko