i have seen popular question of callback here, still not getting why use function pointer in callback instead of used callback via normal function. here's accepted answer (modified) of popular question
void populate_array(int *array, size_t arraysize, int getnextvalue(void)) // note that, here use normal function call. { (size_t i=0; i<arraysize; i++) array[i] = getnextvalue(); } int getnextrandomvalue(void) { return rand(); } int main(void) { int myarray[10]; populate_array(myarray, 10, getnextrandomvalue); ... } as have seen above still can achieve callback implementation via simple function, why use function pointer implement callback. (i.e. why pass reference), when can without that.
also, can implement qsort, bsearch without function pointer provide callback in them. so, why pointer function way.
void populate_array(int *array, size_t arraysize, int getnextvalue(void)) // note that, here use normal function call. this not function call: cannot have function calls inside declarations. getnextvalue pointer function takes no arguments , returns int declared using different syntax.
consider analogy: can define new type pointer int , use in declaration of function
typedef int* intptr_t; void myfunction(intptr_t ptr) { ... } or can ptr pointer int inside declaration:
void myfunction(int* ptr) { ... } in same way, can define type function pointer before using in declaration
typedef void generator_t(void); void populate_array(int *array, size_t arraysize, generator_t getnextvalue) { } or getnextvalue function pointer using alternative syntax post.
one reason use typedef function pointers consistency checking when want create arrays of function pointers: if library function uses function pointer defined inside function's declaration, need re-create same declaration in own code create array of pointers intend pass library pointers. may lead inconsistencies visible @ point of invocation of library function, instead of point of array declaration, making potential issues harder trace.
Comments
Post a Comment