what is "callback function"?.can anyone explain me please..

Submitted by bheema_k2007
on June 20, 2007 - 8:09am

hi all,
what is "callback function"?.can anyone explain me please..
with example..

regards
bheem

It's when you tell a

Anonymous (not verified)
on
June 20, 2007 - 12:25pm

It's when you tell a function to call another function (specified by you) at some point.

#include <stdio.h>

static void count_to_five(int (*print_cb)(const char *))
{
   char str[4];
   int i;

   for (i = 0; i < 5; i++) {
      snprintf(str, sizeof(str), "%d", i);
      (void)print_cb(str);
   }
}

static int custom_puts(const char *str)
{
   printf("foo: %s\n", str);
   return 0;
}

int main(void)
{
   count_to_five(puts);        /* use libc puts() function to print numbers */
   count_to_five(custom_puts); /* use our custom_puts() function to print numbers */
   return 0;
}

In some cases you define a

Anonymous (not verified)
on
June 21, 2007 - 8:50am

In some cases you define a callback to use as a handler for some kind of event. For example, using GTK, you can define a callback function that will be executed when a certain object is clicked.

HTH

Cheers

It's let's you say what to do when something happens.

Anonymous (not verified)
on
June 21, 2007 - 12:09pm

A callback function is a function which you register/ask to be called later, usually as a result of a particular event happening.

You register a function to be called back on a particular event, and may also pass in some data with the registration. When the event occurs the function is called and the data you provided when registering comes in as a parameter (which may be used to determine what the function does, so you can register the same function with different data for different events and get it to do different things).

It's used a lot in X Windows programming. I suspect device drivers can be looked at the same way (you register an "open", "read", etc. handler).

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.