You might already be familiar with callbacks and not realize it. If you've ever used qsort() or bsearch(), or another library function that takes a function pointer as an argument to help it do its work, you have already used callbacks! For example the signature for qsort is
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
and might be used like this
struct foo {
char key[10];
int id;
/* more members */
};
/* comparison function to sort struct foo by key */
int cmpfoo_bykey(const void *vp1, const void *vp2)
{
const struct foo *foo1 = vp1;
const struct foo *foo2 = vp2;
return strcmp(foo1->key, foo2->key);
}
/* comparison function to sort struct foo by id */
int cmpfoo_byid(const void *vp1, const void *vp2)
{
const struct foo *foo1 = vp1;
const struct foo *foo2 = vp2;
return foo1->id - foo2->id;
}
int main()
{
struct foo my_data[100];
/* load data into my_data : not show here*/
/* sort my_data by key field */
qsort(my_data, 100, sizeof(struct foo), cmpfoo_bykey);
/* use my_data in key-ordered way ... */
/* sort my_data by id field */
qsort(my_data, 100, sizeof(struct foo), cmpfoo_byid);
/* use my_data in id-ordered way ... */
return 0;
}
In the above example qsort() knows how to sort an array of items in a generic way, but not how to compare items. It gets around this limitation by using a callback function, that the programmer provides, that does know how to compare items in the array. So, whenever qsort() needs to know how two items in the array compare to each other, it calls back to the code provided by the programmer to determine how the two items compare to each other.
Keep Calm and Carry On