I'm trying out callback functions in C, and I'm not sure why, but for some reason printf does not work in the callback function. For example:
#include <stdio.h>
void call_this_method()
{
printf("call_this_method called\n");
}
void callback(void (*method))
{
printf("callback called\n");
(void) method;
}
int main(int argc, const char * argv[])
{
callback(call_this_method);
}
if I try to run this, only "callback called" gets printed out in the console; "call_this_method called" does not get printed out. Why is that?
First of all void (*method)
is a plain pointer to anything . It's equal to void *method
. You should declare it as a pointer to a function void (*method)(void)
.
Secondly, (void) method
doesn't call anything. It just evaluates method
as a value on its own, and the discards that value (due to the cast). With the above fix you call it like any other function:
method();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.