【C】枚举用例分析

枚举,一种构造类型,用于声明一组命名的常数,当一个变量有几种可能的取值时,可以将它定义为枚举类型。

枚举的目的就是提高程序的可读性;

枚举的特殊属性:

初始化一个枚举类型:

enum day {Sun=0,Mon,Tue,Wed,Thu,Fri,Sat};

定义Sun为0,后面的Mon Tue Wed 就为1 2 3

enum day {Sun,Mon=10,Tue,Wed,Thu,Fri,Sat};

此时Sun为0 Mon=10 Tue=11 Wed=12·······

 

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 enum day {Sun=0,Mon,Tue,Wed,Thu,Fri,Sat};
 5 const char * dds[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
 6 int main(void)
 7 {
 8     enum day dd,yy;
 9     char days[5];
10     printf("please input one day:\n");
11     fgets(days,4,stdin);
12         for(dd=Sun; dd<=Sat; dd++)
13         {
14             if(strcmp(days,dds[dd])==0)  //比较字符串
15             {
16                 break;
17             }
18         }
19         switch(dd)
20         {
21             case Sun:printf("tomorrow is mon\n"); break;
22             case Mon:printf("tomorrow is tue\n"); break;
23             case Tue:printf("tomorrow is wed\n"); break;
24             case Wed:printf("tomorrow is thu\n"); break;
25             case Thu:printf("tomorrow is fri\n"); break;
26             case Fri:printf("tomorrow is sat\n"); break;
27             case Sat:printf("tomorrow is sun\n"); break;
28         }
29     
30 }

你可能感兴趣的:(枚举)