I came up with the following options:
Using the goto statement:
Start:
goto Data
Data:
goto Finish
Finish:
;
using the switch statement:
switch(m_state) {
case State.Start:
m_state = State.Data;
break;
case State.Data:
m_state = State.Finish;
break;
case State.Finish:
break;
}
using goto and switch together:
switch(m_state) {
case State.Start:
goto case State.Data2;
case State.Data1:
goto case State.Finish;
case State.Data2:
m_state = State.Data1;
//call to a function outside the state machine
//that could possibly change the state
break;
case State.Finish:
break;
}
I prefer the first option using the goto statement, because it is faster and less verbose. But i’m not sure if it’s the best option. Performance wise maybe, but when it comes to readability i don’t know. That’s why i ask this question. Which option do you prefer and why?
The advantage with the switch over the goto is that you have the state in a variable, not just in the instruction pointer.
With the goto method the state machine has to be the main loop that controls everything else, because you can’t step out of it because you would lose the state.
With the switch method the state machine is isolated, and you can go anywhere you want to handle events from the outside. When you return to the state machine, it just continues where yuu left off. You can even have more than one state machine running side by side, something that is not possible with the goto version.
I’m not sure where you are going with the third alternative, it looks just like the first alternative with a useless switch around it.