#include <stdio.h>#include <stdint.h>
// 状态和事件定义(指定uint8_t类型节省内存)typedef enum : uint8_t
{
STATE_A,
STATE_B,
STATE_C,
STATE_COUNT
} State;
typedef enum : uint8_t {
EVENT_X,
EVENT_Y,
EVENT_Z,
EVENT_COUNT
} Event;
// 状态表项结构typedef struct {
State next_state;
void (*action)(void);
} TransitionEntry;
// 动作函数void action_A_to_B(void) { printf("Transition
from A to B\n");
}void action_A_to_C(void)
{ printf("Transition from A to C\n");
}void action_B_to_A(void)
{ printf("Transition
from B to A\n"); }void action_B_to_C(void)
{ printf
("Transition from B to C\n");
}void action_C_to_A(void) { printf
("Transition
from C to A\n"); }void action_C_to_B(void)
{ printf
("Transition from C to B\n");
}void action_no_op(void) { /* 无操作 */ }
void action_error(void)
{ printf("Error: Invalid state/event!\n");
}
// 状态表定义const TransitionEntry state_table
[STATE_COUNT][EVENT_COUNT]
= {
[STATE_A] = {
[EVENT_X] = { .next_state = STATE_B, .action
= action_A_to_B },
[EVENT_Y] = { .next_state = STATE_C, .action
= action_A_to_C },
[EVENT_Z] = { .next_state = STATE_A, .action
= action_no_op }
},
[STATE_B] = {
[EVENT_X] = { .next_state = STATE_A, .action
= action_B_to_A },
[EVENT_Y] = { .next_state = STATE_C, .action
= action_B_to_C },
[EVENT_Z] = { .next_state = STATE_B, .action
= action_no_op }
},
[STATE_C] = {
[EVENT_X] = { .next_state = STATE_A, .action
= action_C_to_A },
[EVENT_Y] = { .next_state = STATE_B, .action
= action_C_to_B },
[EVENT_Z] = { .next_state = STATE_C, .action
= action_no_op }
}
};
// 当前状态
State current_state = STATE_A;
// 事件处理函数(含边界检查)void process_event(Event event)
{
// 边界检查:防止数组越界
if (current_state >= STATE_COUNT || event
>= EVENT_COUNT) {
action_error();
current_state = STATE_A; // 复位到初始状态
return;
}
TransitionEntry entry = state_table[current_state][event];
if (entry.action != NULL) {
entry.action();
}
current_state = entry.next_state;
printf("Current state: %d\n", current_state);
}
// 主函数int main(void) {
printf("Starting state table demo...\n");
printf("Initial state: %d\n", current_state);
// 模拟事件序列
Event events[] = { EVENT_X, EVENT_Y,
EVENT_Z,
EVENT_X, 5 }; // 最后一个非法事件测试
for (int i = 0; i < sizeof(events)/sizeof(events[0]);
i++) {
printf("Processing event: %d\n",
events[i]);
process_event(events[i]);
}
return 0;
}