2

I am trying to create a threaded state machine where each state returns a pointer to the next state. I have a number of state machines running so the next state of all these is stored in an array that is sequenced through to call them in a round robin fashion. So what I would like to do is:

pState[i] = (pState[i])();

I understand how to return a function pointer in general but since I need the returned pointer to be a type of function that returns a pointer to a function the recursion is confusing me. The state would look like:

pSatateFunc StateA(void){
// ... code ...
return StateB;
}

So, how do I define this so I can define the array of pointers?

2
  • I know this has been asked before but I can't find the question. But the short answer is no, you can't recursively define function pointers. But there are workarounds (simplest being, have the function return a void* which is cast to a function pointer) Commented Dec 4, 2013 at 21:57
  • Thanks, I was kind of thinking this but thought maybe I was missing something. Commented Dec 4, 2013 at 22:25

1 Answer 1

1

You can't do this directly, but you can do it indirectly by introducing a struct type whose only member is a function pointer:

struct state
{
    struct state (*func)(void);
};

Then your functions are defined to return this type:

struct state StateA(void)
{
    /* ... code ... */
    return (struct state){ StateB };
}

Your pstate array would be of this type too:

struct state pState[N];

/* ... */

pState[i] = pState[i].func();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.