Understanding typedefs for function pointers in C

后端 未结 7 1674
别跟我提以往
别跟我提以往 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.)

提交回复
热议问题