1、什么是枚举
把一个事物所有可能的取值一一列举出来
# include <stdio.h> //只定义了一个数据类型,并没有定义变量, 该数据类型的名字是 enum WeekDay enum WeekDay { MonDay, TuesDay, WednesDay, ThursDay, FriDay, SaturDay, SunDay }; //MonDay 默认的值为0,可以通过MonDay=i修改MonDay默认的值 int main(void) { //int day; //day定义成int类型不合适 enum WeekDay day = SunDay; printf("%d ", day); return 0; } /*-------------------------------------------------------------------- 6 Press any key to continue -----------------------------------------------------------------------*/
2、怎样使用枚举
/* 对枚举的应用! */ # include <stdio.h> enum weekday { MonDay, TuesDay, WednesDay, ThursDay, FriDay, SaturDay, SunDay //考虑将WednesDay改为WednesDay = 5之后,MonDay与SunDay的值是多少? }; //本函数的目的只是期望接受0~6之间的数字,将形参i定义为枚举型,可以有效的避免传参失误的问题 void f(enum weekday i) { switch (i) { case 0: printf("MonDay! "); break; case 1: printf("TuesDay! "); break; case 2: printf("WednesDay! "); break; case 3: printf("ThursDay! "); break; case 4: printf("FriDay! "); break; case 5: printf("SaturDay! "); break; case 6: printf("SunDay! "); break; } } int main(void) { f(FriDay); //虽然FriDay本质上就是5,但直接写成f(5);就是错的, 也不能写成f(10); 考虑为什么! 嘿嘿 return 0; }
3、枚举的优缺点
代码更安全
书写麻烦