Eric
Eric

Reputation: 24880

Usage of typedef on function

What is the difference between the following function typedef:

typedef void tbl_opt (void *tbl_item, void *tbl_param);     // 1
typedef void *tbl_opt (void *tbl_item, void *tbl_param);    // 2
typedef void (*tbl_opt) (void *tbl_item, void *tbl_param);  // 3
typedef (void *) (*tbl_opt) (void *tbl_item, void *tbl_param); // 4

Usually, I use the 3rd & 4th, but I saw the other 2 in a book, which I don't understand well.


[Update] Summary:

It seems when define type in case 1 or 2, when use that type, still need declare a pointer variable, and initialize it to point to another actual function, so I guess that's why case 3 & 4 are more popular.

Upvotes: 1

Views: 75

Answers (2)

ashok v
ashok v

Reputation: 408

3 and 4 are Function Pointers:

  1. A Function that returns void or nothing and takes two void* arguments

    typedef void tbl_opt (void *tbl_item, void *tbl_param);
    
  2. A function that returns a void* and takes two void * arguments

    typedef void *tbl_opt (void *tbl_item, void *tbl_param);  
    
  3. A function pointer to a function that returns void or nothing and takes two void* arguments

    typedef void (*tbl_opt) (void *tbl_item, void *tbl_param); 
    
  4. A Function pointer to a function that returns void* and takes two void* arguments

    typedef (void *) (*tbl_opt) (void *tbl_item, void *tbl_param);
    

Upvotes: 4

Tarc
Tarc

Reputation: 3312

typedef to:

  1. a function getting void pointers and returning void
  2. a function getting void pointers and returning void pointer
  3. a pointer to a function getting void pointers and returning void
  4. a pointer to a function getting void pointers and returning void pointer

by the way, please read Reading C Type Declarations - it will change your life.

Upvotes: 4

Related Questions