gpt4 book ai didi

c - C语言中的状态机

转载 作者:太空狗 更新时间:2023-10-29 16:31:33 26 4
gpt4 key购买 nike

用 C 编写状态机的最佳方法是什么?
我通常在 for(;;) 中写一个大的 switch-case 语句,当外部操作完成时回调以重新进入状态机。
你知道更有效的方法吗?

最佳答案

我喜欢 Quantum Leaps方法。

当前状态是一个指向以事件对象为参数的函数的指针。当事件发生时,只需调用该事件的状态函数;然后该函数可以完成其工作并通过将状态设置为另一个函数来转换到另一个状态。

例如:

// State type and variable, notice that it's a function pointer.
typedef void (*State)(int);
State state;

// A couple of state functions.
void state_xyz(int event) { /*...*/ }
void state_init(int event) {
if (event == E_GO_TO_xyz) {
// State transition done simply by changing the state to another function.
state = state_xyz;
}
}

// main contains the event loop here:
int main() {
int e;
// Initial state.
state = state_init;
// Receive event, dispatch it, repeat... No 'switch'!
while ((e = wait_for_event()) != E_END) {
state(e);
}
return 0;
}

QL 框架为额外的事情提供帮助,例如进入/退出/初始化操作、分层状态机等。我强烈推荐 the book对此进行更深入的解释和良好的实现。

关于c - C语言中的状态机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2271073/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com