Reputation: 541
I am a little bit confused about this subject. I know what callback is but function pointers are a little bit more confusing to me. Can they mean the same thing (at least in C/C++ context)? Or is one of them including the other, like function pointers can be used as a callback or vice versa.
Is there a relationship between function pointers and callbacks, or are they completely different subjects?
Upvotes: 3
Views: 611
Reputation: 223699
Function pointers are often used to implement callbacks. A classic example is the qsort
function:
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
The 4th argument to this function is a function pointer. This will typically point to a function you wrote yourself that the qsort
function will call. Here's an example of how it's used:
int cmp(const void *v1, const void *v2)
{
const int *i1 = v1; // C++ requires cast, C doesn't
const int *i2 = v2; // C++ requires cast, C doesn't
if (*i1 < *i2) {
return -1;
} else if (*i1 > *i2) {
return 1;
} else {
return 0;
}
}
int main()
{
int array[] = { 3, 7, 5, 1, 2, 9, 0, 4 };
qsort(array, 8, sizeof(int), cmp);
}
In this example, cmp
is used to tell the qsort
function how the elements of the list are to be ordered.
Another example of function pointers that is not a callback is if you want to call a particular type of function based on some flag. For example:
void foo(int case_sensitive)
{
int (*cmpfunc)(const char *, const char *);
if (case_sensitive) {
cmpfunc = strcmp;
} else {
cmpfunc = strcasecmp;
}
...
// set strings str1 and str2
...
if (cmpfunc(str1, str2) == 0)) {
printf("strings are equal\n");
} else {
printf("strings are not equal\n");
}
...
// set strings str3 and str4
...
if (cmpfunc(str3, str4) == 0)) {
printf("strings are equal\n");
} else {
printf("strings are not equal\n");
}
...
}
Upvotes: 6