在C语言中,枚举类型(enumerated type)声明符号名称来表示整形常量。使用enum关键字,可以创建一个新“类型”并指定它可具有的值,如:
//创建spectrum作标记名,那enum spectrum作为一个类型名使用
enum spectrum { red, orange, yellow, green, blue, violet};
//使color作为该类型的变量,red、yellow这些符号常量被称为枚举符(enumerator)
enum spectrum color;
(1)enum常量
从技术上看,blue和red为int型常量,这里在默认情况下,常量被赋予0,1,2等。其中,red = 0, orange = 1。
(2)赋值
(3)enum的用法实例
程序示例使用默认值的方案,把red的值设置为0,使之成为指向字符串“red”的指针的索引。
//使用枚举类型的值
#include <stdio.h>
#include <string.h> //提供strcmp()、strchr()函数原型
#include <stdbool.h> //C99特性
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;
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("Roses are green.");
break;
case blue: puts("Bluebells are red.");
break;
case violet: puts("Violets are red.");
break;
}
else
printf("I dont 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'); //查找换行符
if (find) //如果地址不是NULL
*find = '\0'; //在此处放置一个空字符
else
while (getchar() != '\n')
continue; //处理输入行中剩余的字符串
}
return ret_val;
}
运行结果: