Diego Silva
Diego Silva

Reputation: 15

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*);

Upvotes: 1

Views: 83

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

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.

Upvotes: 1

Related Questions