Richard said:
A function is a callback when it calls *back*.
So, if you pass a function pointer to a library
and the library calls it,
then it's reasonable to call it a callback.
Agreed.
Many uses of function pointers aren't like that.
For example, an interpreter that uses a table
to map function names to function pointers.
What about Stephen Sprunk's parsing example upthread?
"Since the command selector is a string,
it can't be used in a switch statement,
and keeping the list of commands and their respective parsers
in an array also makes it very easy to add and remove commands
without touching the core logic.
And, since the list of commands is stored outside said logic,
it also allows different users
to get a different list of valid commands
(or the same commands pointing to different parsers)
just by passing in a different array to the same core logic."
Because the function table
struct parser_record parser_table_user[] = {
{ "FOO", parse_foo },
{ "BAR", parse_bar },
{ "BAZ", parse_baz },
{ NULL, NULL}
};
can be defined in the calling program and passed to parse_main,
the functions (parse_foo, parse_bar and parse_baz)
are callback functions.
Or a struct that contains a function pointer representing a method
(you might consider it a callback if it's set "from outside",
but not if it's just set by the constructor).
It is a callback function
if you pass a reference (pointer) to that struct to another function
which calls it through the pointer set by the constructor.
The bottom line is that pointers to callback functions can be used
to implement run-time polymorphism in C as well as C++.
The code written to operate on object of a "base" type
will still work with objects "derived" from the base type
because it can callback the functions implemented for
the derived type through the function pointers
in the virtual function table (jump table).