Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Coding the State Machine

When I set out to write this article, I originally wanted to find a general-purpose FSM library for C++. I had trouble finding one to my liking; thus, I decided to write my own. I looked at existing code for state machines in several languages, and most of them shared a common theme, whereby the user built a table describing the states, the events, the actions, and the next states. Both states and actions were specified by name. While looking up a state name isn’t a problem (you can use a map class), looking up an action by name is problematic. I didn’t want to rely on runtime type information, nor did I want to fuss with method pointers as values in a map with strings for keys. Instead, I wanted to take a more object-oriented approach. I wanted my states to be classes, and I wanted the actions to be methods inside the states. And as it turned out, coding such a system worked out quite well.

In the end, I was able to build a pattern framework in which I could write my own classes that serve as states, as well as my own class that serves as the driver for the machine. Inside the driver, I can supply the data structures needed as the machine does its thing. In the case of evaluating infix expressions, I needed a couple of stacks; I was able to put those stacks in my driver.

  • + Share This
  • 🔖 Save To Your Account