Hello there
I'm a new member of this board.
Can anyone explain me on some example what callback functions really do?
I found one tutorial about function pointers where concept of callback function is introduced but I didn't find it suitable for understanding.
Can anyone exaplain it in simple terms or even provide a good link?

Thanks

Think of a callback as the poor man's polymorphism. By forcing some code, say from a library, to use a well defined and portable interface, clients can supply the interface and change the behavior of the library without touching the library code. A good example is a sorting function. If you want to let the function sort different types, you can use a callback for comparing them:

void sort ( void *list, int size,
  int (*compare) ( const void *a, const void *b ) );

Then the client code only needs to supply a suitable comparison function to use the sort for multiple types:

int a[];
double b[];
char *c[];

...

sort ( a, N, cmp_int );
sort ( b, N, cmp_dbl );
sort ( c, N, cmp_str );

Another example is changing the behavior of the function entirely. Consider a binary search tree traversal:

void traverse ( struct jsw_node *root,
  void (*action) ( struct jsw_node *node ) )
{
  if ( root == NULL )
    return;

  jsw_inorder_r ( root->link[0], action );
  jsw_inorder_r ( root->link[1], action );
  action ( root );
}

If action prints the contents of the node then you have a postorder print. If action destroys a node then you have a convenient function to destroy the entire tree. These are two wildly different operations, but because the only difference in the implementation is what you do with each node, a callback can be used with a general traverse function for both of them.

Thanks for the answer, but I don't understand how to define callback function? Is it a function pointer or something else.
Regarding your example is sort function a callback function or not? Why is it called callback function?

Thanks

>Is it a function pointer or something else.
It depends on the language. In C it's a pointer to a function. In C++ it's either a pointer to a function or an object that overloads operator().

>Regarding your example is sort function a callback function or not?
No, compare is the callback. sort only uses it.

>Is it a function pointer or something else.
It depends on the language. In C it's a pointer to a function. In C++ it's either a pointer to a function or an object that overloads operator().

>Regarding your example is sort function a callback function or not?
No, compare is the callback. sort only uses it.

Thanks for the answer, I understand now.

P.S. The moment I saw avatar I knew it was you Prelude. Did you finally buy a digital camera? :)

This article has been dead for over six months. Start a new discussion instead.