Search code examples
c++cfunction-pointersesp-idf

Function Pointer Initialization in C/C++


As I was going through a ESP IDF's documentation; I saw that a function pointer was initialized in a certain way that does not make sense to me.

typedef void *app_driver_handle_t;

app_driver_handle_t app_driver_light_init();
app_driver_handle_t app_driver_button_init();

Etc.

I thought that in order to initialize a function pointer, you must do it the following way:

app_driver_handle_t = app_driver_button_init();

Sorry for my beginner level questions.

It would do wonders if someone could explain this.

Thanks


Solution

  • Let's break down the code you're looking at.

    typedef void *app_driver_handle_t;
    

    This is not a function pointer. This is a void pointer, which means it can point to basically any values. And this is a type, not a value, so app_driver_handle_t does not actually contain any pointers at all; it's merely a name that's synonymous with void*.

    app_driver_handle_t = app_driver_button_init();
    

    Given the typedef above, this syntax is never valid. You're setting a type equal to what is presumably a function call. You can't assign to types. Full stop.

    What you can do is declare variables and assign them the result of function calls.

    app_driver_handle_t my_variable;
    my_variable = app_driver_button_init();
    

    or you can do it in one line.

    app_driver_handle_t my_variable = app_driver_button_init();
    

    Finally, these last two lines.

    app_driver_handle_t app_driver_light_init();
    app_driver_handle_t app_driver_button_init();
    

    These are also not function pointers. These are function prototypes. They're a promise to the compiler, saying, "I will eventually define two functions called app_driver_light_init and app_driver_button_init. These two functions will take no arguments and will return a void*". There's still no function pointer happening here. The functions, when they're eventually defined, will return a void*, which, again, is not a function pointer but a pointer to void.