Search code examples
cfunction-pointersdeclarationtypedef

Typedef in c, how it works when it takes 2 arguments


Can anyone explain to me how this code snippet works?

typedef int (*compare)(const char*, const char*);

Solution

  • It is a declaration of an alias for the type pointer to function that has the return type int and two parameters of the type const char *.

    typedef int (*compare)(const char*, const char*);
    

    Using the alias you can declare a variable of the pointer type as shown in the demonstration program below

    #include <string.h>
    #include <stdio.h>
    
    typedef int (*compare)(const char*, const char*);
    
    int main( void )
    {
        compare cmp = strcmp;
        printf( "\"Hello\" == \"Hello\" is %s\n",
                cmp( "Hello", "Hello" ) == 0 ? "true" : "false" );
    }
    

    where strcmp is a standard C string function declared like

    int strcmp(const char *s1, const char *s2);
    

    and the pointer (variable) cmp is initialized by the address of the function.