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?
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.
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.
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).
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.
register
is a C keyword: Use another name for the function.
You have extra parantheses around the callback parameter. It should be:
void funcName(void (*callback) (void))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With