Can anyone explain to me how this code snippet works?
typedef int (*compare)(const char*, const char*);
CodePudding user response:
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.