Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are function pointers really needed for implementing a FSM?

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

I don't quite understand why they chose function pointers. In my understanding pointers to functions are useful when one needs the same interface, but for different types of "events", for example parsing some Internet protocol packet (it's convenient to register one pointer to function and assign to it different functions, one to parse HTTP, second to parse FTP and so on. This is merely an example, but I think you got my point).

But this is not what I see in the article, IMHO for the state machine astraightforward implementation would suffice, or may be I'm wrong?

like image 904
Mark Avatar asked Aug 18 '26 12:08

Mark


1 Answers

The most straightforward way to implement an FSM is via function pointers.
In FSM a mapping is defined that associates an event and a state to a specific behavior.
So depending on the state, the same event should be treated differently. The usage of function pointers is the most appropriate for this.
Additionally it is easily extensible. To add new behavior, you just add new functions and update the mapping table for the new behavior.
Also it can be extended to have multiple statemachines.
I guess there could be other "hacks" to implement an FSM but function pointers is standardized approach.

like image 107
Cratylus Avatar answered Aug 21 '26 03:08

Cratylus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!