Switch 与枚举分支
Coddy 面向 Luau 开发者的 C 课程的第 9 课,共 48 课。
Luau 没有 switch 语句:你可以串联使用 if/elseif,这样最多只会运行一个分支;也可以在表中查找代码,并使用 or 作为回退值。C 的 switch 会跳转到匹配的 case 标签,如果没有用 break 或 return 退出控制流,就会继续执行后续的 case。对于无法识别的整数代码,要保留 default,因为 or 回退值会处理缺失的键。之后,枚举会为这些代码提供易读的名称。
Luau
local code = 2
local names = {[1] = "new", [2] = "paid"}
print(names[code] or "unknown")C17
#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 分支。
挑战
简单当代码为 1 时返回 new,为 2 时返回 paid,其他整数则返回 unknown。返回借用的常量文本;调用方不得释放它。
编辑未锁定的源文件和头文件。确保声明的公共 API 与可见的锁定文件 main.c 兼容,因为它会直接调用该 API。不要添加另一个 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;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Luau 开发者的 C中的所有课
自己练习: C 在线编译器