Sunday, June 28, 2009

Function returning function pointer: funny syntax

Take a look at this:

void (*f())(void*);

At a first glance, it may look like some kind of special function that returns void and takes a void*. That's totally wrong. It's actually a function that takes zero arguments, and returns function pointer, a void (*)(void*) -- that is, a pointer to a function pointer that returns void and takes a void*. The syntax actually makes a little sense if you consider the syntax for defining a variable containing such a function:

void (*f)(void*);

Typedefs of function pointers are weird too:

typedef void (*ptrFunc)(void*);

But I can't help to think that the following syntax would be much clearer:

void (*)(void*) f(); // invented syntax
void (*)(void*) f;
typedef void (*)(void*) ptrFunc;

These would make a lot more sense than the current function pointer syntax in C/C++, and would 'logically match' other declarations -- [return] type followed by an identifier (followed by argument list if it is a function), instead of mixing [return] type, identifier and argument list into one big mess.
It may be that the invented syntax is harder to parse -- I have thought a while on this, but haven't come to a reliable conclusion. The syntax may just be a historical artifact.

In any case, this odd syntax must be the reason why you usually define typedefs for function pointers, as done above. Then we can use the following syntax:

ptrFunc f();
ptrFunc f;

Much cleaner and understandable -- the obvious drawback is: what's a ptrFunc? You'll have to find the typedef to know. But I think that's worth it.

No comments:

Post a Comment