Concept of C++ State Machine

Muhammad Adil Oct 12, 2023
  1. Overview of State Machine in C++
  2. Benefits of State Machine
  3. State Transition in C++
  4. State Machine Class in C++
Concept of C++ State Machine

This tutorial educates us about the concept of a C++ state machine, illustrates how we can use it, and highlights its benefits.

Overview of State Machine in C++

To understand the state machine in C++, we should first know about the concept of a finite-state machine.

A finite-state machine is a mathematical model of computation that captures the idea that a computer can be in one of the states’ finite numbers at any specified time and can be changed between these states as time progresses.

A state machine is composed of states, transitions, and actions. The states are the different conditions that the FSM can be in. The transitions are the actions that cause a change from one state to another.

The actions happen when the FSM changes from one state to another. The C++ language has three keywords that define a state machine: enum, switch, and goto.

An enum defines a set of constants representing each possible state in the FSM. A switch statement checks which state is active and executes an appropriate action.

The Goto is used to jump out of nested loops or switch statements without breaking or returning statements.

Benefits of State Machine

Some of the benefits are listed below:

  • State machines provide an elegant way to express complex behavior through simple transition rules.
  • They are well-suited for modeling specific aspects of real-world systems such as traffic lights, elevators, or even human languages.
  • State machines deconstruct the design into a series of steps or states in state-machine jargon. Each state is responsible for a specific task.
  • In contrast, events are the stimuli that cause the state machine to move, or transition, between states.

State Transition in C++

State transition in C++ state machine code is a process where the state of the program changes from one state to another. An event or condition can trigger the change of states called a trigger.

When a state changes, some actions can be executed, such as printing out messages or changing the color of objects on the screen.

For example, if there is no event for a long time and then an event happens, the transition will be triggered from waiting to default. The C++ programming language provides an easy way to implement a state machine using its switch statement.

State Machine Class in C++

When building your state machine, you’ll need two base classes: StateMachine and EventData. A class derives from StateMachine to get the components required to support state changes and event handling.

The StateMachine header also includes several preprocessor multiline macros to help implement the state machine. The structure needs to be an inheritor of the EventData base class to provide unique data to the state functions.

We can find the source code for the state machine in the files state_machine.cpp and demo.h.

Example Code for state_machine.cpp:

#include <iostream>

#include "demo.h"
using namespace std;
void Execute_State_Machine(void) {
  int 1st_state = 0;
  while (1) {
    char trans_letter;
    cout << "1st state: " << 1st_state << "\n";
    cout << "Enter trans letter: ";
    cin >> trans_letter;
    cin.ignore(100, '\n');
    demo_Entry const* bn = demo_begin();
    demo_Entry const* const p_demo_end = demo_end();
    bool demo_um = false;
    while ((!demo_um) && (bn != p_demo_end)) {
      if (bn->1st_state_id == 1st_state) {
        if (bn->trans_letter == trans_letter) {
          cout << "changing"
               << " from 1st " << 1st_state << ", to 2nd " << bn->pro_state_id
               << "\n";
          1st_state = bn->pro_state_id;
          demo_um = true;
          break;
        }
      }
      ++bn;
    }
    if (!demo_um) {
      cerr << "same\n";
    }
  }
}

Example Code for demo.h:

struct demo_x {
  int 1st_state_id;
  char trans_letter;
  int 2nd_state_id;
};
demo_x const* demo_begin(void);
demo_x const* demo_end(void);

Example Code for demo.cpp:

#include "demo.h"
static const demo_x demo_m[] = {
    {0, 'T', 1},
    {0, 'U', 2},
    {0, 'V', 3},
};
static const int demo = sizeof(demo_m) / sizeof(demo_m[0]);
Table_Entry const* table_begin(void) { return &demo_m[0]; }
Table_Entry const* table_end(void) { return &demo_m[demo]; }

Click here to check the working of the code mentioned above.

Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook