枚举作为整数
1、枚舉作為整數(shù)
在系統(tǒng)內(nèi)部,C語(yǔ)言會(huì)把枚舉變量和常量作為整數(shù)來(lái)處理,默認(rèn)情況下,編譯器會(huì)把整數(shù)0、1、2、3……賦給特定枚舉中的常量。如枚舉city中,GZ、FS、SZ、DG分別被賦值0、1、2、3。
而枚舉變量C1被保存為0,C2為3……
2、枚舉值的取值范圍
當(dāng)定義一個(gè)枚舉變量時(shí),其值可以為enum中定義的枚舉變量,或者任意int類型的值。當(dāng)然,超出enum取值范圍的值沒(méi)有實(shí)際意義。
#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; }輸出結(jié)果:c1=0 ? ?c2=2 ? ?c3=6
而以下程序則編譯不通過(guò):
#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.)
總結(jié)