This page has been designed specifically for the printed screen. It may look different than the page you were viewing on the web.
Please recycle it when you're done reading.

The URI for this page is { http://cc.byexamples.com }

simple callback function Posted on October 11th

Callback function is hard to trace, but sometimes it is very useful. Especially when you are designing libraries. Callback function is like asking your user to gives you a function name, and you will call that function under certain condition.

For example, you write a callback timer. It allows you to specified the duration and what function to call, and the function will be callback accordingly. “Run myfunction() every 10 seconds for 5 times”

Or you can create a function directory, passing a list of function name and ask the library to callback accordingly. “Callback success() if success, callback fail() if failed.”

Lets look at a simple function pointer example

How to pass argument to callback function?
Observered that function pointer to implement callback takes in void *, which indicates that it can takes in any type of variable including structure. Therefore you can pass in multiple arguments by structure.

Trackback URL

Some Responses to “simple callback function” :

  1. Thank you for the example, please make a change in the first snap shot of code.

    void (*callback)(void *);
    to
    void (*callback)(void);

    Commented Vladimir Grekhov on November 10th, 2007.
  2. yup…i agree with vladimir…but we can also do it like this…

    void cbfunc()
    {
    printf(”called”);
    }

    int main ()
    {
    /* function pointer */
    void (*callback)();

    /* point to your callback function */
    callback = &cbfunc;

    /* perform callback */
    callback();

    return 0;
    }

    Commented compumaster - cebu on July 22nd, 2008.
  3. Thanks Vladimir, corrected.
    @cebu, it seems more clean :)

    Commented mysurface on July 22nd, 2008.
Leave your own comments about this post: