Are function pointers necessary for implementing FSM?

I read http://www.netrino.com/Embedded-Systems/How-To/State-Machines-Event-Driven-Systems later in the article they provide an implementation of a small FSM in C.

I don’t quite understand why they chose function pointers. In my understanding, function pointers are useful when you need the same interface, but for different types of “events”, for example, to parse some Internet protocol package (it’s convenient to register one pointer to a function and assign different functions to it, one for parsing HTTP, second for FTP analysis, etc. This is just an example, but I think you understand my point.)

But this is not what I see in this article, IMHO for the implementation of the right machine in real time would be enough, or maybe I'm wrong?

+3
source share
3 answers

First, look at this answer , that is (in my opinion) it’s easier to understand than the one you posted.

Secondly, you are right: function pointers are useful for implementing different behaviors for the same “event pattern”. This is what is commonly called OOP polymorphism (see this wikipedia article ).

, ... , FSM: - , : FSM.

, "" , - .

+2

FSM - .
FSM , .
-. .
, . , .
, statemachines.
, "" FSM, - .

+4

, . , , C, -

#define FSM
#define STATE(x)      s_##x :
#define NEXTSTATE(x)  goto s_##x

FSM {
  STATE(x) {
    ...
    NEXTSTATE(y);
  }

  STATE(y) {
    ...
    if (x == 0) 
      NEXTSTATE(y);
    else 
      NEXTSTATE(x);
  }
}

Some people may refuse to use it gotoin any circumstances, but I think this is one implementation that really uses it pretty nicely.

So, in order to answer your question, yes, I not only think that function pointers may be redundant for FSM, but also tend to obfuscate the code.

+3
source

Source: https://habr.com/ru/post/1777869/


All Articles