Home > Blogs > 30 C++ Tips in 30 Days: Tip # 6 simplify complex pointer to function declarations

30 C++ Tips in 30 Days: Tip # 6 simplify complex pointer to function declarations

By  Nov 24, 2007

Topics: Programming, C/C++

Pointers to functions syntax is scary enough, but when you need to declare an array of pointers to functions, or worse yet – declare a function that returns a pointer to another function, the syntax can be totally indecipherable, even for experts, unless you simplify it.

Can you tell for example what the following declaration means? 

void (*p[12]) (void (*)()); 

p is an array of 12 pointers to a function that has the following signature: it returns void and takes a pointer to another function with no arguments and with a void return type. In both C++ and English, the easiest way to understand such complex declarations is breaking them to smaller entities first. First declare a typedef for the notion "a pointer to a function returning void and taking no arguments": 

typedef void (*pfv)(); 

Next, declare another typedef for the notion "a pointer to a function returning void and taking pfv": 

typedef void (*pf_taking_pfv) (pfv);

Now declaring an array of 12 such pointers is a cinch: 

//equivalent to
//void (*p[12]) (void (*)()); but much more readable:

 pf_taking_pfv p[12];

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.

Other Things You Might Like

Xamarin Unleashed

Xamarin Unleashed