前言

enum Day
{mon, tue, wed, thu, fir, sat, sun};
枚举类型是为了减少繁多的整数定义。诸如mon(默认=0),tue这些是枚举符(int类型的常量)对应一个数字。

  • 可以给枚举列表中的常量赋值
  • 没有赋值的枚举符会根据前面被赋予的常量++

概念

mon, tue,把这些看作常量。

定义

1
2
3
4
enum Day    //Day是类型名,可不写
{
mon, tue, wed = 1, thu, fir, sat, sun
}day; //变量名

用法

  • 给枚举变量赋值,然后输出
1
2
3
4
5
6
7
8
9
10
11
12
enum Day
{
mon, tue, wed, thu, fir, sat, sun
};

int main()
{
enum Day day;//定义变量
day = tue;
printf("%d", day);
return 0;
}
  • 可以用for循环遍历元素(要依赖连续的++值,中间不能有赋值)
1
2
for(day = wed; day <= sun; day++)
printf("%d ",day); //输出1, 2, 3, 4,5

示例

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/* enum.c -- uses enumerated values */
#include <stdio.h>
#include <string.h> // for strcmp(), strchr()
#include <stdbool.h> // C99 feature
char * s_gets(char * st, int n);
//枚举类型(常量的数组)
enum spectrum {red, orange, yellow, green, blue, violet};
//字符串数组
const char * colors[] = {"red", "orange", "yellow",
"green", "blue", "violet"};
#define LEN 30

int main(void)
{
char choice[LEN];
enum spectrum color;//定义color变量表示枚举符(常量)
bool color_is_found = false;

puts("Enter a color (empty line to quit):");
while (s_gets(choice, LEN) != NULL && choice[0] != '\0')
{
for (color = red; color <= violet; color++)//常量的使用
{
if (strcmp(choice, colors[color]) == 0)
{
color_is_found = true;
break;
}
}
if (color_is_found)
switch(color)
{
case red : puts("Roses are red.");
break;
case orange : puts("Poppies are orange.");
break;
case yellow : puts("Sunflowers are yellow.");
break;
case green : puts("Grass is green.");
break;
case blue : puts("Bluebells are blue.");
break;
case violet : puts("Violets are violet.");
break;
}
else
printf("I don't know about the color %s.\n", choice);
color_is_found = false;
puts("Next color, please (empty line to quit):");
}
puts("Goodbye!");

return 0;
}

char * s_gets(char * st, int n)
{
char * ret_val;
char * find;

ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n'); // look for newline
if (find) // if the address is not NULL,
*find = '\0'; // place a null character there
else
while (getchar() != '\n')
continue; // dispose of rest of line
}
return ret_val;
}