Search code examples
cfunction-pointersdeclarationtypedefimplicit-conversion

what happens here: typedef int (*ptr) (void) in .h file C


I have a piece of C code and don't understand what happens here:

typedef int (*ptr) (void *ptr2, const char *name);

What I do understand is the typedef int (*ptr) part, but what happens in the second()? I've seen some questions where it was the other way around: typedef void (*ptr) (int), is this similar or different (and how)? I'm not the best at C, so I thought maybe *ptr now points to a function where *ptr2 and *name are declared or *ptr now points to *ptr2 and *name?

It would be great if someone could explain this to me. Thanks in advance!


Solution

  • If you have for example a function declaration like

    int f( void *ptr2, const char *name );
    

    (as it is seen the function type is int( void *, const char * )) then a pointer to the function will look like

    int ( *pf )( void *, const char * ) = f;
    

    and the type of the pointer pf is int ( * )( void *, const char * ). That is the pointer pf now contains the address of the function f.

    To introduce an alias for this function pointer type you can write

    typedef int (*ptr) (void *ptr2, const char *name);
    

    In this case the above declaration of the pointer pf will look like

    ptr pf = f;
    

    that is the declaration of the pointer is simplified.

    Pay attention to that the function name used as an initializer of the pointer is implicitly converted to a pointer to the function. That is you could write

    ptr pf = &f;
    

    but due to the implicit conversion it is enough to write

    ptr pf = f;