Understanding typedefs for function pointers in C

后端 未结 7 1598
别跟我提以往
别跟我提以往 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:21
    int add(int a, int b)
    {
      return (a+b);
    }
    int minus(int a, int b)
    {
      return (a-b);
    }
    
    typedef int (*math_func)(int, int); //declaration of function pointer
    
    int main()
    {
      math_func addition = add;  //typedef assigns a new variable i.e. "addition" to original function "add"
      math_func substract = minus; //typedef assigns a new variable i.e. "substract" to original function "minus"
    
      int c = addition(11, 11);   //calling function via new variable
      printf("%d\n",c);
      c = substract(11, 5);   //calling function via new variable
      printf("%d",c);
      return 0;
    }
    

    Output of this is :

    22

    6

    Note that, same math_func definer has been used for the declaring both the function.

    Same approach of typedef may be used for extern struct.(using sturuct in other file.)

    0 讨论(0)
  • 2020-11-22 11:22

    A function pointer is like any other pointer, but it points to the address of a function instead of the address of data (on heap or stack). Like any pointer, it needs to be typed correctly. Functions are defined by their return value and the types of parameters they accept. So in order to fully describe a function, you must include its return value and the type of each parameter is accepts. When you typedef such a definition, you give it a 'friendly name' which makes it easier to create and reference pointers using that definition.

    So for example assume you have a function:

    float doMultiplication (float num1, float num2 ) {
        return num1 * num2; }
    

    then the following typedef:

    typedef float(*pt2Func)(float, float);
    

    can be used to point to this doMulitplication function. It is simply defining a pointer to a function which returns a float and takes two parameters, each of type float. This definition has the friendly name pt2Func. Note that pt2Func can point to ANY function which returns a float and takes in 2 floats.

    So you can create a pointer which points to the doMultiplication function as follows:

    pt2Func *myFnPtr = &doMultiplication;
    

    and you can invoke the function using this pointer as follows:

    float result = (*myFnPtr)(2.0, 5.1);
    

    This makes good reading: http://www.newty.de/fpt/index.html

    0 讨论(0)
  • 2020-11-22 11:25

    cdecl is a great tool for deciphering weird syntax like function pointer declarations. You can use it to generate them as well.

    As far as tips for making complicated declarations easier to parse for future maintenance (by yourself or others), I recommend making typedefs of small chunks and using those small pieces as building blocks for larger and more complicated expressions. For example:

    typedef int (*FUNC_TYPE_1)(void);
    typedef double (*FUNC_TYPE_2)(void);
    typedef FUNC_TYPE_1 (*FUNC_TYPE_3)(FUNC_TYPE_2);
    

    rather than:

    typedef int (*(*FUNC_TYPE_3)(double (*)(void)))(void);
    

    cdecl can help you out with this stuff:

    cdecl> explain int (*FUNC_TYPE_1)(void)
    declare FUNC_TYPE_1 as pointer to function (void) returning int
    cdecl> explain double (*FUNC_TYPE_2)(void)
    declare FUNC_TYPE_2 as pointer to function (void) returning double
    cdecl> declare FUNC_TYPE_3 as pointer to function (pointer to function (void) returning double) returning pointer to function (void) returning int
    int (*(*FUNC_TYPE_3)(double (*)(void )))(void )
    

    And is (in fact) exactly how I generated that crazy mess above.

    0 讨论(0)
  • 2020-11-22 11:31

    This is the simplest example of function pointers and function pointer arrays that I wrote as an exercise.

        typedef double (*pf)(double x);  /*this defines a type pf */
    
        double f1(double x) { return(x+x);}
        double f2(double x) { return(x*x);}
    
        pf pa[] = {f1, f2};
    
    
        main()
        {
            pf p;
    
            p = pa[0];
            printf("%f\n", p(3.0));
            p = pa[1];
            printf("%f\n", p(3.0));
        }
    
    0 讨论(0)
  • 2020-11-22 11:36

    A very easy way to understand typedef of function pointer:

    int add(int a, int b)
    {
        return (a+b);
    }
    
    typedef int (*add_integer)(int, int); //declaration of function pointer
    
    int main()
    {
        add_integer addition = add; //typedef assigns a new variable i.e. "addition" to original function "add"
        int c = addition(11, 11);   //calling function via new variable
        printf("%d",c);
        return 0;
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题