1.枚举
枚举是一种用户定义的数据类型,关键字是 enum,语法是:
enum 枚举类型名字{名字0, … , 名字n};枚举类型名字 通常并不真的使用,用的是 大括号里边的名字(它们是常量符号,类型是 int,值依次是 0 到 n-1)
- enum colors{red, yellow, green};
- 创建了3个变量,red的值是0,yellow的值是1,green的值是2
- 当需要一些可以排列起来的常量值时,定义枚举的意义就是给这些常量值起个名字
#include<stdio.h>
enum COLOR {
RED,
BLUE,
GREEN
};
int main(int argc, char const *argv[])
{
printf("请输入一个颜色:");
int color = -1;
scanf("%d", &color);
char *colorName = NULL;
switch(color){
case RED:
colorName = "Red"; // 输入 0,输出 Red
break;
case BLUE:
colorName = "Blue";
break;
case GREEN:
colorName = "Green";
break;
default:
colorName = "Unknown";
break;
}
printf("你选择的颜色是:%s\n", colorName);
return 0;
}
2.自动计数的枚举
#include<stdio.h>
enum COLOR{
RED,
YELLOW,
GREEN,
ColorNums
};
int main(int argc, const char *argv[])
{
int color = -1;
// 枚举量与数组下标一一对应
char *colorNames[ColorNums] = {
"red",
"yellow",
"green"
};
char *colorName = NULL;
printf("请出入颜色代码:");
scanf("%d", &color);
if(color >= 0 && color < ColorNums){
colorName = colorNames[color]; // 输入0, 输出 red
} else {
colorName = "unknown";
}
printf("你输入的颜色是:%s\n", colorName);
return 0;
}
3.枚举只是int
枚举量可以作为值
enum 枚举类型 可以作为类型
实际上内部计算和外部输入输出时 都是 整数
#include<stdio.h>
enum color {
red,
yellow,
green
};
void f(enum color c);
int main(int argc, char const *argv[])
{
enum color c = red;
printf("请输入一个颜色:");
scanf("%d", &c);
f(c);
return 0;
}
void f(enum color c)
{
// 打印输入的数字,输入 0 输出 0。输入 5,输出 5
printf("%d\n", c);
}
#include<stdio.h>
enum COLOR {
RED = 1,
YELLOW,
GREEN = 5,
ColorNums
};
int main(int argc, const char *argv)
{
enum COLOR color = RED;
printf("code for YELLOW is %d\n", YELLOW); // code for YELLOW is 2
printf("color is %d\n", color); // color is 1
printf("ColorNums is %d\n", ColorNums); // ColorNums is 6
return 0;
}
4.总结
- 有意义上排比的名字,用枚举比 const int 方便
- 枚举比宏好,因为枚举有int类型
- 枚举类型虽然可以当做类型使用,但是很少用,不好用