Reputation: 3513
Here's the question that asked: What is a “callback” in C and how are they implemented?
and one of the answer in that question is like this: (I slightly modified to print the value also)
#include <stdio.h>
#include <stdlib.h>
void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
for (size_t i=0; i<arraySize; i++) {
array[i] = getNextValue();
printf("%d\n", array[i]); // This is what I added
}
}
int getNextRandomValue(void)
{
return rand();
}
int main(void)
{
int myarray[10];
populate_array(myarray, 10, getNextRandomValue);
}
Now my question is the what is the use of callback function in above, when I can do it without callback also?
#include <stdio.h>
#include <stdlib.h>
void populate_array(int *array, size_t arraySize, int getNextValue(void))
{
for (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 you please give me real example of callback function which cannot be done with simple function?
Upvotes: 0
Views: 143
Reputation:
Now my question is the what is the use of callback function in above, when I can do it without callback also?
Nothing, really - it's not a real-life example, it was intended just to explain how a callback works.
Also, can you please give me real example of callback function which cannot be done with simple function?
The cURL library uses read, write and various other callback functions when it needs that the user provide data (for example, when making a HTTP POST request) or when it wants to inform the user of data retrieval (for example, when the server sends HTTP headers). While this could be done using temporary buffers, dynamic memory allocation and "property setter" functions, it's much more convenient (i. e. it requires less legwork) using the callback function approach.
Upvotes: 3