我是靠谱客的博主 心灵美冬日,最近开发中收集的这篇文章主要介绍C语言实现简单状态机,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

  1. 使用switch
enum State {
    STATE_A,
    STATE_B,
    STATE_C
};

enum Event {
    EVENT_1,
    EVENT_2,
    EVENT_3
};

void state_machine(enum State* state, enum Event event) {
    switch (*state) {
        case STATE_A:
            if (event == EVENT_1) {
                *state = STATE_B;
            } else if (event == EVENT_2) {
                *state = STATE_C;
            }
            break;
        case STATE_B:
            if (event == EVENT_3) {
                *state = STATE_A;
            }
            break;
        case STATE_C:
            if (event == EVENT_1) {
                *state = STATE_A;
            } else if (event == EVENT_3) {
                *state = STATE_B;
            }
            break;
    }
}
  1. 表方法
enum State {
    STATE_A,
    STATE_B,
    STATE_C
};

enum Event {
    EVENT_1,
    EVENT_2,
    EVENT_3
};

struct Transition {
    enum State current_state;
    enum Event event;
    enum State next_state;
};

struct Transition state_transitions[] = {
    {STATE_A, EVENT_1, STATE_B},
    {STATE_A, EVENT_2, STATE_C},
    {STATE_B, EVENT_3, STATE_A},
    {STATE_C, EVENT_1, STATE_A},
    {STATE_C, EVENT_3, STATE_B}
};

enum State state_machine(enum State current_state, enum Event event) {
    for (int i = 0; i < sizeof(state_transitions) / sizeof(state_transitions[0]); i++) {
        if (state_transitions[i].current_state == current_state &&
            state_transitions[i].event == event) {
            return state_transitions[i].next_state;
        }
    }
    return current_state;
}
  1. 函数指针
enum State {
    STATE_A,
    STATE_B,
    STATE_C
};

enum Event {
    EVENT_1,
    EVENT_2,
    EVENT_3
};

struct StateMachine {
    enum State current_state;
    void (*state_handlers[3])(enum Event);
};

void state_a_handler(enum Event event) {
    if (event == EVENT_1) {
        state_machine.current_state = STATE_B;
    } else if (event == EVENT_2) {
        state_machine.current_state = STATE_C;
    }
}

void state_b_handler(enum Event event) {
    if (event == EVENT_3) {
        state_machine.current_state = STATE_A;
    }
}

void state_c_handler(enum Event event) {
    if (event == EVENT_1) {
        state_machine.current_state = STATE_A;
    } else if (event == EVENT_3) {
        state_machine.current_state = STATE_B;
    }
}

struct StateMachine state_machine = {
    .current_state = STATE_A,
    .state_handlers = {
        state_a_handler,
        state_b_handler,
        state_c_handler
    }
};

void state_machine_handle_event(enum Event event) {
    state_machine.state_handlers[state_machine.current_state](event);
}

最后

以上就是心灵美冬日为你收集整理的C语言实现简单状态机的全部内容,希望文章能够帮你解决C语言实现简单状态机所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(72)

评论列表共有 0 条评论

立即
投稿
返回
顶部