[ back to toc ]

callback function in C

Date: 2002/03/13 09:40


I don't clearly understand using callback functions. I know what function
pointer is but I don't know usage. I am actually analyzing source codes,
where registering event-handlers, handler, callback functions and so on
are being used.

Can you give me simple compile-available-C-coded example, which shows how
to register functions, how to use that registerd-event handlers and how
callback is working? Please gime me that example I can fully get the
concepts and usage.

Thanks in advance.


A call-back function is a parameter that you pass to a function telling
the function what other function to call in some cases. Confusing
formulated this way? No problem, I explain in an example.

You have a function that reads a number from a file character by character
and returns the converted long value. The function prototype can be:

long get_long_from_file(FILE *fp);

If you want to practice you can code this for your pleasure to train
yourself. This works fine so long as long you realize that you need a
function, similar to this one, but the characters come from socket. Thus
you write another function that has the prototype:

long get_long_from_socket(SOCKET s);

A week passes and you develop your code further. You realize that this
time you need a function that does the same, but the characters are stored
in a database table. You function prottype now looks the following:

long get_long_from_db(DBHANDLE db);

After many weeks you realize that there is a bug in the conversion routine
and the same bug is repeated in the three functions. You correct it three
places and test all three functions to ensure correctness.

Is this the simplest way to go? Certainly not.

What you could do is write a general function that has the prototype:

long get_long(char *(*getcharfun()),void *);

To call this funtion to get the long from the opened file you can call:

mylong = get_long(getc,fp);

I have wrote a full sample program that reads only a single character from
the file and is called to read from the standard input:

#include <stdio.h>

long get_long(char *(*getchar()), void *p){
return (long)getchar(p);


I tested it on Linux.


[ back to toc ]