Switch 与枚举分支
Coddy 面向 Python 开发者的 C 课程的第 9 课,共 48 课。
Python 的 if/elif 会选择一个分支。C 的 switch 在 case 后可能会继续执行,除非通过 break 或 return 退出。对于无法识别的整数代码,请保留 default。之后,枚举会为这些代码提供易读的名称。
Python
code=2
print({1:"new",2:"paid"}.get(code,"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 的 case 末尾明确结束执行。
挑战
简单当代码为 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;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Python 开发者的 C中的所有课
自己练习: C 在线编译器