I am familiar with some Java and C#
A callback is an event or delegate in those languages - a way to get your code run by somebody else's code in it's context. Hence, the term "callback":
- You call some other piece of code
- It runs, perhaps calculating an intermediate value
- It calls back into your code, perhaps giving you that intermediate value
- It continues running, eventually passing control back to you by completing
A canonical example is a sort routine with a user defined comparison function (the callback). Given a sort routine such as:
void Sort(void* values, int length, int valueSize,
int (*compare)(const void*, const void*)
{
for (int i = 0; i < length; i = i + 2) {
// call the callback to determine order
int isHigher = compare(values[i], values[i + 1]);
/* Sort */
}
}
(The specifics of how the sort is performed isn't important - just focus on the fact that any sorting algorithm needs to compare 2 values and determine which is higher.)
So, now we can define some comparison functions:
int CompareInts(const void* o, const void* p) {
int* a = (int*) o;
int* b = (int*) p;
if (a == b) return 0;
return (a < b) ? -1 : 1;
}
int ComparePersons(const void* o, const void* p) {
Person* a = (Person*) o;
Person* b = (Person*) p;
if (a == b) return 0;
return (a->Value() < b=>Value()) ? -1 : 1;
}
And reuse the same sort function with them:
int intValues[10];
Person personValues[10];
Sort(intValues, 10, sizeof(intVaues[0]), CompareInts);
Sort(personValues, 10, sizeof(personVaues[0]), ComparePersons);
Things get a bit more complicated if you're using member functions, as you have to manage the this
pointer - but the concept is the same. As with most things, it's easier to explain them in C first. ;)