Monday, October 15, 2012

Using cdecl to explain function pointers in C: Examples, hints and tips, please - Stack Overflow

Neat; hadn't seen cdecl before.

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.
share|improve this answer

'via Blog this'

No comments:

Post a Comment