What are callback function ?
how are they implemented and where they are useful ?
As well as the traditional uses people have already described, callbacks
really come into their own when you're doing GUI programming.
Typically, the main thread will just run in a loop, waiting for events
to occur - for example, for the user to move his mouse in your window,
or click one of your buttons. The GUI framework will provide a mechanism
for you to pass it function pointers, which it will then associate with
certain events. When an event occurs, the event loop will invoke any
callback functions you've provided for that event. Often, the callback
function will have parameters, and the event dispatcher will provide you
with extra information about the event (perhaps the exact x,y
coordinates of the mouse, for example) through the arguments it calls
your callback function with.
As a simple example, using GTK (a popular and portable GUI framework for
C), you can have code like this:
void callback(GtkWidget *widget, gpointer data)
{
g_print("Hello world!\n");
}
int main(int argc, char **argv)
{
GtkWidget *button;
/* do some initialization - omitted here */
gtk_signal_connect(GTK_OBJECT(button), "clicked",
GTK_SIGNAL_FUNC (callback), NULL);
/* start the event loop - when button is clicked, callback will be
* invoked */
gtk_main();
return 0;
}