enumerate
enum enumeration type {enumeration value list};
Enumeration is to list every possible value one by one.
For example, in the multiple-choice questions we do, four possible options are listed, and let us choose the most likely one.
There are 12 months in the month, and they can also be listed one by one.
enum Month //月份
{
Jan,
Feb,
Mar,
Apr,
May,
Jun,
Jul,
Aug,
Sep,
Oct,
Nov,
Dec
};
enum type definition
enum Day//星期
{
Mon,
Tues,
Wed,
Thur,
Fri,
Sat,
Sun
};
enum Day and enum Month are
all possible values in the enumeration type {}, that is, enumeration constants.
These possible values all have values. By default, the first one starts from 0 and increments by 1 at a time. You can also assign an initial value at the beginning of the definition.
For example:
default
assign initial value
Enum Type Use Cases
call enum type variable
enum Color
{
red,green,blue
};
int main()
{
enum Color a, b, c; //创建枚举类型变量
a = blue;
b = red; //赋值
c = green;
printf("%d %d %d", a, b, c);
return 0;
}
Specific use cases
#include <stdio.h>
enum weekday {
mon=1, tue, wed, thu, fri, sat ,sun } day; //初始化mon=1,创建变量day。
int main()
{
int n;
printf("请输入1到7的数:");
scanf("%d", &n);
day = (enum weekday)n; //类型转换
switch (day)
{
case mon: printf("monday\n"); break;
case tue: printf("tuesday\n"); break;
case wed: printf("wednesday\n"); break;
case thu: printf("thursday\n"); break;
case fri: printf("friday\n"); break;
case sat: printf("satday\n"); break;
case sun: printf("sunday\n"); break;
default: printf("输入错误\n"); break;
}
return 0;
}
Enter a number to print the day of the week.