# C enum(枚举)

`enum　枚举名　{枚举元素1,枚举元素2,……};`

#define MON 1 #define TUE 2 #define WED 3 #define THU 4 #define FRI 5 #define SAT 6 #define SUN 7

```enum DAY
{
MON=1, TUE, WED, THU, FRI, SAT, SUN
};```

`enum season {spring, summer=3, autumn, winter};`

### 枚举变量的定义

1、先定义枚举类型，再定义枚举变量

```enum DAY
{
MON=1, TUE, WED, THU, FRI, SAT, SUN
};
enum DAY day;```

2、定义枚举类型的同时定义枚举变量

```enum DAY
{
MON=1, TUE, WED, THU, FRI, SAT, SUN
} day;```

3、省略枚举名称，直接定义枚举变量

```enum
{
MON=1, TUE, WED, THU, FRI, SAT, SUN
} day;```

## 实例

#include<stdio.h> enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN }; int main() { enum DAY day; day = WED; printf("%d",day); return 0; }

`3`

## 实例

#include<stdio.h> enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN } day; int main() { // 遍历枚举元素 for (day = MON; day <= SUN; day++) { printf("枚举元素：%d n", day); } }

```枚举元素：1

```

```enum
{
ENUM_0,
ENUM_10 = 10,
ENUM_11
};```

## 实例

#include <stdio.h> #include <stdlib.h> int main() { enum color { red=1, green, blue }; enum color favorite_color; /* ask user to choose color */ printf("请输入你喜欢的颜色: (1. red, 2. green, 3. blue): "); scanf("%d", &favorite_color); /* 输出结果 */ switch (favorite_color) { case red: printf("你喜欢的颜色是红色"); break; case green: printf("你喜欢的颜色是绿色"); break; case blue: printf("你喜欢的颜色是蓝色"); break; default: printf("你没有选择你喜欢的颜色"); } return 0; }

```请输入你喜欢的颜色: (1. red, 2. green, 3. blue): 1

## 实例

#include <stdio.h> #include <stdlib.h> int main() { enum day { saturday, sunday, monday, tuesday, wednesday, thursday, friday } workday; int a = 1; enum day weekend; weekend = ( enum day ) a; //类型转换 //weekend = a; //错误 printf("weekend:%d",weekend); return 0; }

`weekend:1`