枚举作为整数

mac2022-06-30  21

1、枚举作为整数

在系统内部,C语言会把枚举变量和常量作为整数来处理,默认情况下,编译器会把整数0、1、2、3……赋给特定枚举中的常量。如枚举city中,GZ、FS、SZ、DG分别被赋值0、1、2、3。

而枚举变量C1被保存为0,C2为3……

2、枚举值的取值范围

当定义一个枚举变量时,其值可以为enum中定义的枚举变量,或者任意int类型的值。当然,超出enum取值范围的值没有实际意义。

#include <stdio.h> int main(void){ enum city{GZ, FS, SZ, GD}; enum city c1, c2, c3; c1=GZ; c2=SZ; c3=6; printf("c1=%d\tc2=%d\tc3=%d",c1, c2, c3); return 0; } 输出结果:c1=0    c2=2    c3=6

而以下程序则编译不通过:

#include <stdio.h> int main(void){ enum city{GZ, FS, SZ, GD}; enum city c1, c2, c3; c1=GZ; c2=SZ; c3=BJ; printf("c1=%d\tc2=%d\tc3=%d",c1, c2, c3); return 0; }

E:\B C\my_codes\CProgrammingAModernApproach>gcc testenum.c testenum.c: In function `main': testenum.c:9: error: `BJ' undeclared (first use in this function) testenum.c:9: error: (Each undeclared identifier is reported only once testenum.c:9: error: for each function it appears in.)

转载于:https://www.cnblogs.com/jinhong-lu/archive/2013/02/08/4559565.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)