0

Possible Duplicate:
What is the point of function pointers?

I saw this code

 void (*foo)(int);

And I understood that is pointer to function.

Why should I point to another function what does it give me?

Community
  • 1
  • 1
user1758424
  • 87
  • 1
  • 8

3 Answers3

1

You can use it to store a handler function that can be changed according the program flow, like the comparison function supplied to qsort.

void (*my_handler)(int);

void set_handler(void(*fn)(int)) {
    my_handler = fn;
}

void do_stuff() {
    // ...
    my_handler(x); // using a custom handler
}

if (something) {
    set_handler(my_function_1);
}
else set_handler(my_function_2);    

do_stuff(); 
Murilo Vasconcelos
  • 4,677
  • 24
  • 27
0

You can inject so a compairer for a sort algorithm. So you can exclude some logic outside.

Or you can implement a callback with this method for some event handling.

rekire
  • 47,260
  • 30
  • 167
  • 264
0

Function pointers are commonly used for callbacks. For example, imagine an asynchronous function that does some heavy work and you want to be notified when its finished:

void doWork(void (*foo)(int));

When you call that function, it runs in its own thread so it returns immediately. How do you know when it's finished? You tell it to call a function you provide when it's done:

void myFoo(int n);

and you pass that to doWork():

doWork(myFoo);

Now when doWork() finishes, it will call myFoo().

That's just one use of callbacks, but it's the most common one, I believe.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96