here's question asked: what “callback” in c , how implemented?
and 1 of answer in question this: (i modified print value also)
#include <stdio.h> #include <stdlib.h> void populate_array(int *array, size_t arraysize, int (*getnextvalue)(void)) { (size_t i=0; i<arraysize; i++) { array[i] = getnextvalue(); printf("%d\n", array[i]); // added } } int getnextrandomvalue(void) { return rand(); } int main(void) { int myarray[10]; populate_array(myarray, 10, getnextrandomvalue); } now question use of callback function in above, when can without callback also?
#include <stdio.h> #include <stdlib.h> void populate_array(int *array, size_t arraysize, int getnextvalue(void)) { (size_t i=0; i<arraysize; i++) { array[i] = getnextvalue(); printf("%d\n", array[i]); } } int getnextrandomvalue(void) { return rand(); } int main(void) { int myarray[10]; populate_array(myarray, 10, getnextrandomvalue); } also, can please give me real example of callback function cannot done simple function?
now question use of callback function in above, when can without callback also?
nothing, - it's not real-life example, intended explain how callback works.
also, can please give me real example of callback function cannot done simple function?
the curl library uses read, write , various other callback functions when needs user provide data (for example, when making http post request) or when wants inform user of data retrieval (for example, when server sends http headers). while done using temporary buffers, dynamic memory allocation , "property setter" functions, it's more convenient (i. e. requires less legwork) using callback function approach.
Comments
Post a Comment