C 的 枚举与switch语句

等级 5317 次按键

定义包含四种状态的 enum,以及一个用 switch 为每种状态打印可读名称的函数。分别用 IDLE、RUNNING、STOPPED 调用,打印 Idle、Running、Stopped。

C 代码

// 枚举常量从 0 开始递增:IDLE=0、RUNNING=1、PAUSED=2、STOPPED=3
1enum State { IDLE, RUNNING, PAUSED, STOPPED };
2
// 打印某个状态的可读名称
3void printState(enum State s) {
// 跳转到与 s 匹配的 case 标签
4 switch (s) {
// 每种状态一个 case;break 防止继续执行下一个 case
5 case IDLE: printf("Idle\n"); break;
6 case RUNNING: printf("Running\n"); break;
7 case PAUSED: printf("Paused\n"); break;
8 case STOPPED: printf("Stopped\n"); break;
9 }
10}
11
// 打印 Idle
12printState(IDLE);
// 打印 Running
13printState(RUNNING);
// 打印 Stopped;这里没有用到 PAUSED
14printState(STOPPED);

运行结果

Idle
Running
Stopped
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 C 代码中需要输入的符号及其出现次数。

  • ;× 12
  • (× 9
  • )× 9
  • "× 8
  • :× 4
  • \× 4
  • ,× 3
  • {× 3
  • }× 3

C 等级 5 的更多代码示例

← 返回 C 打字练习