?
本文檔使用 PHP中文網(wǎng)手冊 發(fā)布
一個枚舉類型是獨(dú)特的類型,它的值是其值基本類型(見下面),其中包括明確命名常數(shù)(的值枚舉常數(shù))。
枚舉類型使用以下枚舉說明符作為聲明語法中的類型說明符進(jìn)行聲明:
enum identifier(optional) { enumerator-list } |
---|
其中,枚舉器列表是逗號分隔的列表(允許使用尾隨逗號)(自C99以來)的枚舉器,其中每個列表的形式為:
enumerator | (1) | |
---|---|---|
enumerator = constant-expression | (2) |
其中
identifier, enumerator | - | identifiers that are introduced by this declaration |
---|---|---|
constant-expression | - | integer constant expression whose value is representable as a value of type int |
與結(jié)構(gòu)體或聯(lián)合體一樣,引入枚舉類型和一個或多個枚舉常量的聲明也可以聲明該類型或類型的一個或多個對象。
enum color_t {RED, GREEN, BLUE}, c = RED, *cp = &c; // introduces the type enum color_t // the integer constants RED, GREEN, BLUE // the object c of type enum color_t // the object cp of type pointer to enum color_t
每個出現(xiàn)在枚舉說明符主體中的枚舉器都會成為一個int
在封閉范圍內(nèi)具有類型的整數(shù)常量,并且可以在需要整數(shù)常量時使用(例如,作為 case 標(biāo)簽或非 VLA 數(shù)組大?。?。
enum color_t { RED, GREEN, BLUE} r = RED;switch(r) { case RED : puts("red"); break; case GREEN : puts("green"); break; case BLUE : puts("blue"); break;}
如果枚舉器后跟=常量表達(dá)式,則其值是該常量表達(dá)式的值。如果枚舉器后面沒有= constant-expression,那么它的值是比同一個枚舉中前一個枚舉器的值大1的值。第一個枚舉器的值(如果它不使用= constant-expression)為零。
enum Foo { A, B, C=10, D, E=1, F, G=F+C};//A=0, B=1, C=10, D=11, E=1, F=2, G=12
標(biāo)識符本身(如果使用)成為標(biāo)記名稱空間中枚舉類型的名稱,并且需要使用關(guān)鍵字 enum(除非將 typedef 放入普通名稱空間中)。
enum color_t { RED, GREEN, BLUE};enum color_t r = RED; // OK// color_t x = GREEN: // Error: color_t is not in ordinary name spacetypedef enum color_t color;color x = GREEN; // OK
每個枚舉類型與下列之一兼容:char
有符號整數(shù)類型或無符號整數(shù)類型。它是實(shí)現(xiàn)定義的,哪種類型與任何給定枚舉類型兼容,但無論它是什么,它必須能夠表示該枚舉的所有枚舉值。
枚舉類型是整數(shù)類型,因此可以在其他整數(shù)類型可以使用的任何位置使用,包括隱式轉(zhuǎn)換和算術(shù)運(yùn)算符。
enum { ONE = 1, TWO } e;long n = ONE; // promotiondouble d = ONE; // conversione = 1.2; // conversion, e is now ONEe = e + 1; // e is now TWO
與 struct 或 union 不同,C 中沒有前向聲明的枚舉:
enum Color; // Error: no forward-declarations for enums in Cenum Color { RED, GREEN, BLUE};
枚舉允許以比其更方便和結(jié)構(gòu)化的方式聲明命名常量#define
; 它們在調(diào)試器中可見,遵守范圍規(guī)則并參與類型系統(tǒng)。
#define TEN 10struct S { int x : TEN; }; // OK
或者
enum { TEN = 10 };struct S { int x : TEN; }; // also OK
C11 standard (ISO/IEC 9899:2011):
6.2.5/16 Types (p: 41)
6.7.2.2 Enumeration specifiers (p: 117-118)
C99 standard (ISO/IEC 9899:1999):
6.2.5/16 Types (p: 35)
6.7.2.2 Enumeration specifiers (p: 105-106)
C89/C90 standard (ISO/IEC 9899:1990):
3.1.2.5 Types
3.5.2.2 Enumeration specifiers
enum
.