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?
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?
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();
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.
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.