Switch 与枚举情况
Coddy 面向 Ruby 开发者的 C 课程的第 9 课,共 48 课。
Ruby 的 case/when 只会执行一个分支,不会贯穿执行后续分支,并且可以匹配范围或类。C 的 switch 会跳转到整数常量 case 标签,并继续执行后续 case,除非控制流通过 break 或 return 退出。对于无法识别的整数代码,要保留 default。之后,枚举会为这些代码提供易读的名称。
Ruby
code = 2
label = case code
when 1 then "new"
when 2 then "paid"
else "unknown"
end
puts labelC17
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
int main(void) {
int code=2;switch(code){case 1:puts("new");break;case 2:puts("paid");break;default:puts("unknown");}
return 0;
}
移植规则
如果不需要贯穿执行后续分支,就要在 switch 的 case 中明确结束执行。
挑战
简单代码为 1 时返回 new,为 2 时返回 paid,其他任何整数都返回 unknown。返回借用的常量文本;调用方不得释放它。
编辑未锁定的源文件和头文件。确保声明的公共 API 与可见的锁定文件 main.c 兼容,该文件会直接调用它。不要添加另一个 main。除非任务明确检查取值范围,否则所有数值任务测试数据都足够小,不会溢出。只打印指定的输出;如果提供了驱动程序,它会负责解析输入并生成输出。
亲手试试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int n;if(scanf("%d",&n)!=1)return 1;puts(status_name(n));return 0;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 C中的所有课
自己练习: C 在线编译器