Menu
CoddyTech

switch 语句与枚举情况

Coddy 面向 C# 开发者的 C 课程的第 9 课,共 48 课。

C# 会阻止非空 switch 分支自然贯穿执行。C 允许这种行为,因此显式使用 break 或 return 很重要。C17 不支持现代 C# 的模式匹配或 switch 表达式。

switch 会选择整数分支。使用 break 可防止意外贯穿执行,并使用 default 处理不匹配的值。

C# 示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
class Program {

static void Main(){
int code=2;switch(code){case 1:Console.WriteLine("new");break;case 2:Console.WriteLine("paid");break;default:Console.WriteLine("unknown");break;}
}
}

C# 输出:

paid

C 示例

#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;
}

C 输出:

paid
challenge icon

挑战

简单

代码为 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;}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C# 开发者的 C中的所有课

自己练习: C 在线编译器