温馨提示×

如何用C语言switch case构建状态机

小樊
140
2024-06-13 22:17:47
栏目: 编程语言

在C语言中可以使用switch case语句来构建状态机。下面是一个简单的示例:

#include <stdio.h>

typedef enum {
    STATE_IDLE,
    STATE_RUNNING,
    STATE_PAUSED,
    STATE_STOPPED
} State;

int main() {
    State currentState = STATE_IDLE;
    char input;

    while(1) {
        switch(currentState) {
            case STATE_IDLE:
                printf("Currently in idle state. Press 'r' to start running.\n");
                break;
            
            case STATE_RUNNING:
                printf("Currently running. Press 'p' to pause, 's' to stop.\n");
                break;
            
            case STATE_PAUSED:
                printf("Currently paused. Press 'r' to resume, 's' to stop.\n");
                break;
            
            case STATE_STOPPED:
                printf("Currently stopped. Press 'r' to start running again.\n");
                break;
        }

        input = getchar();

        switch(currentState) {
            case STATE_IDLE:
                if(input == 'r') {
                    currentState = STATE_RUNNING;
                }
                break;
            
            case STATE_RUNNING:
                if(input == 'p') {
                    currentState = STATE_PAUSED;
                } else if(input == 's') {
                    currentState = STATE_STOPPED;
                }
                break;
            
            case STATE_PAUSED:
                if(input == 'r') {
                    currentState = STATE_RUNNING;
                } else if(input == 's') {
                    currentState = STATE_STOPPED;
                }
                break;
            
            case STATE_STOPPED:
                if(input == 'r') {
                    currentState = STATE_RUNNING;
                }
                break;
        }
    }

    return 0;
}

在这个示例中,我们定义了一个枚举类型State来表示状态机的不同状态。在主函数中,我们使用一个while循环来不断检查当前状态并根据输入改变状态。通过使用switch case语句,我们可以根据当前状态打印不同的提示信息,并根据输入来改变状态。这样就构建了一个简单的状态机。

0