Understanding typedefs for function pointers in C

后端 未结 7 1677
别跟我提以往
别跟我提以往 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条回答
  •  萌比男神i
    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.

提交回复
热议问题