Roland Roland - 1 year ago 90
C Question

comp.lang.c faq: Function that can return a pointer to a function of the same type

The following is Question 1.22 from the comp.lang.c faq.

Why is the definition of


typedef int (*funcptr)(); /* generic function pointer */
typedef funcptr (*ptrfuncptr)(); /* ptr to fcn returning g.f.p. */

funcptr start(), stop();
funcptr state1(), state2(), state3();

void statemachine()
ptrfuncptr state = start;

while(state != stop)
state = (ptrfuncptr)(*state)();

funcptr start()
return (funcptr)state1;

Answer Source

The key to understanding the code is 4.13 from the C faq:

It is guaranteed, however, that all function pointers can be interconverted, as long as they are converted back to an appropriate type before calling

We have a function that returns a pointer to a function of the same type. But since we can't define that directly in C we employ a trick. We just make the function return a generic function pointer and then cast it to the appropriate type. We are allowed to do that because of 4.13 above.

Why is funcptr a generic pointer? Isn't it a pointer to a function that returns int? Why is that generic?

According to 4.13 all function pointers can be interconverted so it doesn't really matter how we define it. Just make sure to cast it to the right type before calling it.

Why is the definition of ptrfuncptr necessary?

Because that is the type of the state functions, they are functions that return a function pointer.

Shouldn't the code return (funcptr)state1; in the function start() be return (ptrfuncptr)state1;? Because state1 is a pointer to a fuction returning funcptr?

What start() actually returns is a ptrfuncptr but we defined it as a fuction returning funcptr therefore we just cast the result to funcptr. We cast it to the correct type in the statemachine: state = (ptrfuncptr)(*state)();

Why not define all the state functions with the right type to begin with instead of doing all the pointer casting?

Because this would lead to an infinite recursive definition. Try it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download