Reputation: 3513
I have seen almost all popular question of callback here, but still not getting why use function pointer in callback instead of simply used callback via normal function. Here's the accepted answer (modified) of a popular question
void populate_array(int *array, size_t arraySize,
int getNextValue(void)) // Note that, here I use normal function call.
{
for (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 you have seen above that still I can achieve callback implementation via simple function, so why use function pointer to implement callback. (i.e. why pass reference), when I can do without that.
Also, we can implement qsort, bsearch
without function pointer to provide callback in them. So, why do with pointer to function way.
Upvotes: 2
Views: 447
Reputation: 726479
void populate_array(int *array, size_t arraySize,
int getNextValue(void)) // Note that, here I use normal function call.
This is not a function call: you cannot have function calls inside declarations. getNextValue
is a pointer to function that takes no arguments and returns an int
declared using a different syntax.
Consider this analogy: you can define a new type for a pointer to int
and use it in a declaration of a function
typedef int* intptr_t;
void myFunction(intptr_t ptr) {
...
}
or you can say that ptr
is a pointer to int
inside the declaration:
void myFunction(int* ptr) {
...
}
In the same way, you can define the type for your function pointer before using it in a declaration
typedef void generator_t(void);
void populate_array(int *array, size_t arraySize, generator_t getNextValue) {
}
or you could say that getNextValue
is a function pointer using the alternative syntax from your post.
One reason to use a typedef
for function pointers is consistency checking when you want to create arrays of function pointers: if your library function uses a function pointer defined inside that function's declaration, you would need to re-create the same declaration in your own code to create an array of pointers that you intend to pass to the library as pointers. This may lead to inconsistencies that would be visible only at the point of invocation of the library function, instead of the point of array declaration, making potential issues somewhat harder to trace.
Upvotes: 2