示例
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
// 枚举类型的目的是为了提高程序的可读性和可维护性。
// 定义枚举 {常量值(int)}
enum spectrum {red, orange, yellow, green, blue, violet};
// 也可以指定常量值
enum levels {low = 100, medium = 500, high = 2000};
// cat=0, lynx=10, puma=11, tiger=12
enum feline {cat, lynx = 10, puma, tiger};
//enum
// 声明枚举变量
enum spectrum color;
int main(int argc, char* argv[])
{
int c;
color = blue;
if (color == yellow)
{
}
// 枚举值实际上是int类型
for (color = red; color <= violet; color++)
{
}
// 只要是能使用整型常量的地方就可以使用枚举常量
printf("red = %d, orange = %d\n", red, orange);
/*
虽然枚举符(如red和blue)是int类型,但是枚举变量可以是任意整数类型,前提是该整数类型
可以储存枚举常量。例如,spectrum的枚举符范围是0~5,所以编译器可以用unsigned char来表示
color变量。
*/
/*
注意:C枚举的一些特性并不适用于C++。例如,C允许枚举变量使用++运算符,但是C++标准
不允许。所以,如果编写的代码将来会并入C++程序,那么必须把上面的color声明为int类型,
才能C和C++都兼容。
*/
system("pause");
return 0;
}