I have been reading up on callbacks in C, but I am a bit confused. I know you can pass a function as a parameter just like any other variable / pointer, but why? Why not just call the function normally instead of through a passed pointer?
I have been reading up on callbacks in C, but I am a bit confused. I know you can pass a function as a parameter just like any other variable / pointer, but why? Why not just call the function normally instead of through a passed pointer?
I think there are two major ways callbacks are used. It facilitates code reuse for one; when qsort() was invented, you were expected to use a callback to actually compare things in your array. Instead of rewriting qsort for every possible data entity, you only need to write part of it. So you'll see this used a lot in some libraries. For example, go here and look at all the typedefs of function pointers in the API and where they are used. Feel free to snoop around. And for two, slightly less often, you see a callback will be used in a place where something else could be used, like a switch.
Last edited by whiteflags; 11-27-2011 at 07:38 PM.
What if the function needs to be called at some point in the future? A library, for example, might be able to call one of your functions if it encounters something unexpected. You pass it a function during the initialization phase, and the library stores a copy of the pointer somewhere. If an exceptional circumstance arises, it calls your function.Why not just call the function normally instead of through a passed pointer?
If the function you pass your function pointer to calls the function immediately, with no new context, then sure, there's probably no need for it. But that's not what typically happens. Instead, it calls the function with some unknown data (this is whiteflags' qsort() example), or it calls it at some unknown time.