枚举类型是基本类型,枚举类型是有限的成员的罗列。
格式:
enum 枚举类型名{
成员1,
成员2,
成员3=10,
...
成员n
};
特点:
1.如果成员1没有值,默认的值是0
2.成员的值是依次递增的
3.如果中途出现了新的值,后面的值就从新值开始递增
4.枚举成员之间用 逗号 分隔
5.枚举的成员一旦定义后,就是一个常量
6.枚举的大小是 4 字节
7.当局部变量和枚举成员重名时,枚举成员的值就被隐藏了,使用的是局部变量的值
例:
#include <stdio.h>
enum Color{
black,
white,
green,
blue=10,
red,
pink,
yellow
};
int main(int argc, const char *argv[])
{
enum Color c1 = red;
//对枚举变量直接赋整形值是可以的,但是我们不这么用
//一般而言 枚举变量就用枚举成员赋值
enum Color c2 = 200;
printf("%d\n",c1);
printf("%d\n",c2);
printf("%ld\n",sizeof(enum Color));//4 和枚举成员个数无关
return 0;
}
枚举变量的其他定义方式
enum Color{
black,
green,
blue=10,
yellow
}c1;
enum Color c2;
enum{//省略枚举类型名的定义方式,这种方式就没法定义其他枚举变量了
black,
green,
blue=10,
yellow
}c1;
//枚举和 typedef 连用
#include <stdio.h>
typedef enum Color{
black,
white,
green,
blue=10,
pink,
yellow
}my_enum;//相当于给枚举类型 enum Color 起个别名叫 my_enum
int main(int argc, const char *argv[])
{
enum Color c1 = red;
my_enum c2 = green;
printf("%d\n",c1);
printf("%d\n",c2);
return 0;
}