C语言的枚举 枚举这个类型,其实不是很常见,因为使用define
基本都可以搞定,不过存在即是合理 ,枚举可以让某些数据组合更加简洁、易读、规范。
举个用的最多的例子,如果我们定义一个星期,可以使用define
,如下所示:
1 2 3 4 5 6 7 #define MONDAY 1 #define TUESDAY 2 #define WEDNESDAY 3 #define THURSDAY 4 #define FRIDAY 5 #define SATURDAY 6 #defind SUNDAY 7
看着还是很不错的表达方式,然后我们在看看枚举变量,表达如下:
1 2 3 4 enum DAY { MONDAY = 1 , TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };
看起来貌似更加简洁,明了。
OK,现在来看看枚举的定义方式:
1 enum enum_name { enum_element1, enum_element2, enum_element3...enum_elementN};
其中:
enum_name为枚举的名字
enum_element为枚举的元素
NOTE : 枚举的元素,默认第一个为0,如果需要改变,需要显式初始。
看一下enum的使用吧:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #include <stdio.h> int main () { int i; enum DAY { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }; for (i = MONDAY; i <= SUNDAY; i++) printf ("TODAY is %d\n" , i); return 0 ; }
可以看到默认MONDAY为0,与我们的习惯不同,我们显式初始化为1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #include <stdio.h> int main () { int i; enum DAY { MONDAY = 1 , TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }; for (i = MONDAY; i <= SUNDAY; i++) printf ("TODAY is %d\n" , i); return 0 ; }
看看enum和switch的配合使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 #include <stdio.h> int main () { int i; enum DAY { MONDAY = 1 , TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }; enum DAY which_day ; printf ("Which day is today?[1-7]: " ); scanf ("%d" , &which_day); switch (which_day) { case MONDAY: case TUESDAY: case WEDNESDAY: case THURSDAY: case FRIDAY: printf ("OMG, Working day\n" ); break ; case SATURDAY: case SUNDAY: printf ("Oh, yeah, weekend\n" ); break ; default : printf ("range (1-7)" ); break ; } return 0 ; }
编译运行 直接输入make
就可以了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ALL : enum1 enum2 enum3 enum1: enum1.c gcc -o enum1 enum1.c enum2: enum2.c gcc -o enum2 enum2.c enum3: enum3.c gcc -o enum3 enum3.c .PHONY : clean clean: rm -f enum1 enum2 enum3
运行输出如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 $./enum1 TODAY is 0 TODAY is 1 TODAY is 2 TODAY is 3 TODAY is 4 TODAY is 5 TODAY is 6 $ ./enum2 TODAY is 1 TODAY is 2 TODAY is 3 TODAY is 4 TODAY is 5 TODAY is 6 TODAY is 7 $ ./enum3 Which day is today?[1-7]: 3 OMG, Working day $ ./enum3 Which day is today?[1-7]: 6 Oh, yeah, weekend