Understanding typedefs for function pointers in C

后端 未结 7 1675
别跟我提以往
别跟我提以往 2020-11-22 11:16

I have always been a bit stumped when I read other peoples\' code which had typedefs for pointers to functions with arguments. I recall that it took me a while to get around

7条回答
  •  迷失自我
    2020-11-22 11:40

    Use typedefs to define more complicated types i.e function pointers

    I will take the example of defining a state-machine in C

        typedef  int (*action_handler_t)(void *ctx, void *data);
    

    now we have defined a type called action_handler that takes two pointers and returns a int

    define your state-machine

        typedef struct
        {
          state_t curr_state;   /* Enum for the Current state */
          event_t event;  /* Enum for the event */
          state_t next_state;   /* Enum for the next state */
          action_handler_t event_handler; /* Function-pointer to the action */
    
         }state_element;
    

    The function pointer to the action looks like a simple type and typedef primarily serves this purpose.

    All my event handlers now should adhere to the type defined by action_handler

        int handle_event_a(void *fsm_ctx, void *in_msg );
    
        int handle_event_b(void *fsm_ctx, void *in_msg );
    

    References:

    Expert C programming by Linden

提交回复
热议问题