Anonymous user
Finite state machine: Difference between revisions
m
→{{header|C}}
m (→{{header|C}}) |
|||
Line 72:
=={{header|C}}==
Here is a manually-constructed table-driven finite state machine that
<lang C>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
typedef enum State { READY, WAITING, REFUND, DISPENSE, COLLECT, QUIT
typedef struct statechange {
Line 86 ⟶ 87:
} statechange;
#define MAXINPUTS 3
typedef struct FSM {
const State state;
const statechange table[
▲ const statechange table[3]; // hacky. would be dynamic in a real program.
} FSM;
void Ready(void)
void Waiting(void) {
void Refund(void) {
void Dispense(void) {
void Collect(void) {
void Quit(void)
const FSM fsm[] = {
{ READY, &Ready, {{'D', WAITING}, {'Q', QUIT }, {-1, READY} }},
{ WAITING, &Waiting, {{'S', DISPENSE}, {'R', REFUND}, {-1, WAITING} }},
{ REFUND, &Refund, {{ -1, READY} }},
{ DISPENSE, &Dispense, {{ -1, COLLECT} }},
{ COLLECT, &Collect, {{'C', READY}, { -1, COLLECT } }},
{ QUIT, &Quit, {{ -1, QUIT} }},
};
int each;
State state = READY;
each = 0;
// -1 comes last and is catchall: exit, or loop to self, on no valid input.
if (fsm[state].table[each].in < 0) { state = fsm[state].table[each].out; break; }▼
return 0;
}
|