Search code examples
c++embeddedc++98

Using ranges of an enum for simple state tracking


I am using a series of enums used for state management on an embedded system.

What I am now implementing is a system to display the state of particular modules in a simplistic way to a user. So I would like to translate these various states to 3 super states, in this case red/yellow/green to indicate error/configuring/running.

The simple way I have implemented it thus far is as follows.

enum State
{
  StateAA = 0,
  StateAB,
  StateAC,
  
  StateBA = 100,
  StateBB,
  StateBC,
  
  StateCA = 200,
  StateCB
};

void DisplayState(State st)
{
    if(st < 100)
        displayColor = red;
    else if(st < 200)
        displayColor = yellow;
    else
        displayColor = green;
}

This allows changes to the enum to be managed without adjusting the display function, so long as the ranges are not changed.

However this feels a bit hacky, and I am having trouble wording the question in order to find a better answer. Any suggestions would be appreciated.


Solution

  • That looks "hacky" indeed. Instead consider using a state machine where each state in turn uses its own internal state machine. This internal state should be of no concern to the rest of the program but privately encapsulated.

    Also avoid assigning values to the enum manually, if you don't then you can use the enum type as array index, which is handy. And if you don't, you can also use the old school trick of a State_n member at the end, which then corresponds to the number of states used. (Which is turn can be static_assert against arrays etc to ensure program integrity.)