举出c语言不按顺序执行的代码例子
时间: 2023-10-19 19:27:21 浏览: 117
以下是一个简单的C语言状态机示例,其中通过switch语句实现非顺序执行:
```c
#include <stdio.h>
int main() {
enum State {STATE_START, STATE_A, STATE_B, STATE_C, STATE_END};
enum State currentState = STATE_START;
int input;
while (currentState != STATE_END) {
switch (currentState) {
case STATE_START:
printf("Enter A to go to state A, B to go to state B, or C to go to state C: ");
scanf(" %c", &input);
if (input == 'A') {
currentState = STATE_A;
} else if (input == 'B') {
currentState = STATE_B;
} else if (input == 'C') {
currentState = STATE_C;
}
break;
case STATE_A:
printf("You are in state A. Enter any key to go back to the start state: ");
scanf(" %c", &input);
currentState = STATE_START;
break;
case STATE_B:
printf("You are in state B. Enter any key to go back to the start state: ");
scanf(" %c", &input);
currentState = STATE_START;
break;
case STATE_C:
printf("You are in state C. Enter any key to go back to the start state: ");
scanf(" %c", &input);
currentState = STATE_START;
break;
}
}
return 0;
}
```
在这个示例中,程序根据用户的输入进入不同的状态,而不是按照顺序执行。通过switch语句和枚举类型,状态机可以实现非顺序执行的功能。
阅读全文