枚举
枚举 enum
枚举 enum 也和int struct 一样,是一种数据类型。
在使用上enum有些类似struct ,在效果上和#define相同。
typedef enum Week { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7 }Weekday1,Weekday2;
比如上面这个例子,使用typedef定义了一个枚举类型Week,同时还用该类型声明了2个未初始化的变量Weekday1 Weekday2
这里要注意枚举里的成员,只能是整形,所以即便我们不赋初值,系统也会按照顺序给枚举里的类型自动赋值
比如:
typedef enum Week { Monday = 1, Tuesday , Wednesday , Thursday , Friday , Saturday , Sunday }Weekday1,Weekday2;
这段代码的效果和上一个完全相同。
系统自动为后面的Tuesday 等成员按顺序+1赋了值。
接下来看一下如何给枚举里的成员赋值
首先不使用typdef,这里展现了4种赋值方式
#include <stdio.h> enum Week { Monday = 1, Tuesday , Wednesday , Thursday , Friday , Saturday , Sunday } Weekday1 = Monday,Weekday2 = Tuesday,Weekday4; int main() { enum Week Weekday3 = Friday; int Weekday5 = Saturday; Weekday4 = Sunday; printf("Monday = %d\n",Weekday1); printf("Tuesday = %d\n",Weekday2); printf("Friday = %d\n",Weekday3); printf("Saturday = %d\n",Weekday5); printf("Sunday = %d\n",Weekday4); return 0; }
输出结果如下:
接下来使用typedef
#include <stdio.h> typedef enum Week //这个Week可以不写 { Monday = 1, Tuesday , Wednesday , Thursday , Friday , Saturday , Sunday }Weekday,Zhou; int main() { enum Week Weekday3 = Friday; int Weekday5 = Saturday; Weekday Weekday4 = Sunday; Zhou Weekday2 = Tuesday; // printf("Monday = %d\n",Weekday1); printf("Tuesday = %d\n",Weekday2); printf("Wednesday = %d\n",Wednesday); printf("Friday = %d\n",Weekday3); printf("Saturday = %d\n",Weekday5); printf("Sunday = %d\n",Weekday4); return 0; }
输出结果如下:
枚举变量(Monday、Tuesday等)只能为右值
不能使用这种方法将其赋值
Monday = 18; //错误的做法