Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing callback functions in C

Tags:

c

I am a newbie to C. I am trying to implement callback function using function pointers.

I am getting an error

:test_callback.c:10: error: expected identifier or ‘(’ before ‘void’

when I try to compile the following program:

#include<stdio.h>

void (*callback) (void);

void callback_proc ()
{
  printf ("Inside callback function\n");
}

void register ((void (*callback) (void)))
{
  printf ("Inside registration \n");
  callback (); /* Calling an initial callback with function pointer */
}

int main ()
{
  callback = callback_proc;/* Assigning function to the function pointer */
  register (callback);/* Passing the function pointer */
  return 0;
}

What is this error?Can anyone help?

like image 624
user329013 Avatar asked Apr 29 '10 15:04

user329013


People also ask

How do you implement a callback function?

A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function. console.

What is callback function and how it works in C?

A callback is any executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at a given time [Source : Wiki]. In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called as a Callback function.

Why are callback functions used in C?

Callback functions are an essential and often critical concept that developers need to create drivers or custom libraries. A callback function is a reference to executable code that is passed as an argument to other code that allows a lower-level software layer to call a function defined in a higher-level layer(10).

What is a handler callback in C?

The callback is basically any executable code that is passed as an argument to other code, that is expected to call back or execute the argument at a given time.


2 Answers

  1. register is a C keyword: Use another name for the function.

  2. You have extra parantheses around the callback parameter. It should be:

    void funcName(void (*callback) (void))
    
like image 79
interjay Avatar answered Nov 15 '22 07:11

interjay


I would recommend to use a typedef

#include<stdio.h>

typedef void (*callback_t) (void);
callback_t callback;

void callback_proc(void)
{
    printf ("Inside callback function\n");
}

void reg( callback_t _callback )
{
    printf ("Inside registration \n");
    _callback();
}

int main ()
{
    callback = callback_proc;
    reg(callback);

    return 0;
}

EDIT: removed the register issue

like image 20
stacker Avatar answered Nov 15 '22 07:11

stacker