0

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?

Paco G
  • 391
  • 1
  • 3
  • 15
  • 1
    replace `(void) method;` with `method();` – John Feb 03 '20 at 15:05
  • 1
    and `void (*method)` with `void (*method)(void)`. `void (*method)` is just `void *method` - it's a `void*` pointer. – KamilCuk Feb 03 '20 at 15:05
  • Does this answer your question? [How do function pointers in C work?](https://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work) – John Feb 03 '20 at 15:08

1 Answers1

6

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();
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621