[英]Use of enums in c
I have this enum: 我有这个枚举:
enum Seasons{
winter,spring,summer,autumn
};
what will this code do? 该代码将做什么?
enum Seasons curr_season;
curr_season = autumn;
curr_season = 19;
Thank you! 谢谢!
enum Seasons{
winter,spring,summer,autumn
};
The above creates the following 上面创建了以下内容
winter=0, spring=1, summer=2 and autumn=3
NOTE: enums
are just integers! 注意: enums
只是整数! .. It can take negative numbers also! ..也可以取负数!
enum Seasons curr_season;
curr_season = autumn;
/* curr_season will now have 3 assigned */
curr_season = 19;
/* curr_season will now have 19 assigned */
You can run the following code to check this! 您可以运行以下代码进行检查!
#include <stdio.h>
enum Seasons{
winter,spring,summer,autumn
};
void print_seanons(void)
{
printf("winter = %d \n", winter);
printf("spring = %d \n", spring);
printf("summer = %d \n", summer);
printf("autumn = %d \n", autumn);
return;
}
int main(void)
{
enum Seasons curr_season;
print_seanons();
curr_season = autumn;
printf("curr_season = %d \n", curr_season);
curr_season = 19;
printf("curr_season = %d \n", curr_season);
return 0;
}
Enums constants are of type int
in c. 枚举常量在c中的类型为int
。 Although enum
s are not explicitly of type int
, the conversion between enumerated types, and int
s is silent. 尽管enum
并非显式为int
类型,但枚举类型和int
之间的转换是静默的。 There is usually no constraint checking on enums, so your code is functionally equivalent to: 通常没有对枚举的约束检查,因此您的代码在功能上等效于:
int curr_season;
curr_season = 3;
curr_season = 19;
Enums are integral values, so it will assign the value 19 to curr_season
. 枚举是整数值,因此它将为curr_season
分配值19。
Cross use (assigning integer values to an enum) is considered poor programming practice and should be avoided. 交叉使用(将整数值分配给枚举)被认为是不良的编程习惯,应避免使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.