枚举 1
# include <stdio.h> //只定义了一个数据类型,并没有定义变量, 该数据类型的名字是 enum WeekDay , 默认 值是用0开始 // MonDay = 0 , TuesDay = 1 .... , SunDay = 6 enum WeekDay { MonDay, TuesDay, WednesDay, ThursDay, FriDay, SaturDay, SunDay }; int main(void) { //int day; //day定义成int类型不合适 enum WeekDay day = SunDay; printf("%d ", day); return 0; }
枚举 2
# include <stdio.h> //只定义了一个数据类型,并没有定义变量, 该数据类型的名字是 enum WeekDay , 值是用A的ASC2码开始 // MonDay = 65 , TuesDay = 66 .... enum WeekDay { MonDay = 'A', TuesDay, WednesDay, ThursDay, FriDay, SaturDay, SunDay }; int main(void) { //int day; //day定义成int类型不合适 enum WeekDay day = SunDay; printf("%d ", day); return 0; }
对枚举的应用
/* 对枚举的应用! */ # include <stdio.h> enum weekday { MonDay, TuesDay, WednesDay, ThursDay, FriDay, SaturDay, SunDay //考虑将WednesDay改为WednesDay = 5之后,MonDay与SunDay的值是多少? }; void f(enum weekday i) //本函数的目的只是期望接受0~6之间的数字,将形参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; }