Search code examples
c++cfunction-pointerstypedef

typedef void (*print_type) (const char*);


While exploring some code, I found the following in a header file:

typedef void (*print_type) (const char*);

What does this line mean? I know that typedef is used to make specific word (in our case *print_type) to represent a specific type (in our case const char*).

But my question is why we have to use void?


Solution

  • This:

    void foo(const char*);
    

    declares foo as a function that takes a const char* argument and returns void (i.e., it doesn't return anything). (It would have to be defined somewhere for you to be able to call it.)

    This:

    void (*bar)(const char*);
    

    defines bar as a pointer object. It's a pointer to a function that has the same type as foo, above.

    By adding the typedef keyword, this:

    typedef void (*print_type)(const char*);
    

    defined print_type, not as an object of that pointer-to-function type, but as an alias for that pointer-to-function type.