Anna
Anna

Reputation: 39

How to use typedef of a function?

typedef bool key_equiv_fn(key x, key y);
typedef int key_hash_fn(key x);

What does this mean? How to define a variable such as key_equiv_fn* equiv;

Upvotes: 1

Views: 1238

Answers (2)

syntagma
syntagma

Reputation: 24324

What does this mean?

Let's look at:

typedef bool key_equiv_fn(key x, key y);
          ^         ^ 
       return  name of the    ^      ^
       value   *pointer type* arguments of the functions
               of the         both of type 'key'
               function

How to define a variable such as key_equiv_fn* equiv

#include <stdbool.h>
typedef int key;
typedef bool key_equiv_fn(key x, key y);

// Create a function we will assign to the pointer

bool are_equal(key x, key y) { return x == y; }

int main() {
  key_equiv_fn *your_pointer;
  your_pointer = are_equal;        // assign are_equal address to the pointer
  bool equal = your_pointer(4, 2); // call the function
  return 0;
}

Upvotes: 1

Pras
Pras

Reputation: 4044

You can use function pointers with typedefs as below, I have provided code as example:

#include<stdio.h>
typedef struct _key/*For example*/
{
char keyy[24];
int len;
}key;

int key_equiv_fn(key x,key y) /*Function defination*/
{
 printf("Hello");
return 0;
}

typedef int (key_equiv_fn_ptrType)(key,key); /*Declare function pointer */

int main()
{
key_equiv_fn_ptrType *ptr;
ptr = key_equiv_fn;/*assign key_equiv_fn address to function pointer ptr*/
 key xx;
 key yy;
xx.len = 16;
ptr(xx,yy);/*Call function key_equiv_fn using pointer ptr*/
return 0;
}

Upvotes: 0

Related Questions