?
? ????? PHP ??? ???? ??? ?? ??
C 類型系統(tǒng)中的每個(gè)單獨(dú)類型都具有該類型的多個(gè)限定版本,對(duì)應(yīng)于 const,volatile 中的一個(gè),兩個(gè)或全部三個(gè),并且對(duì)于指向?qū)ο箢愋偷闹羔?,限制限定符。該頁面描述?const 限定符的影響。
用 const 限定類型聲明的對(duì)象可能被編譯器放置在只讀存儲(chǔ)器中,如果程序中永遠(yuǎn)不會(huì)獲取const對(duì)象的地址,它可能根本就不存儲(chǔ)。
const
語義僅適用于左值表達(dá)式; 每當(dāng)在不需要左值的上下文中使用常量左值表達(dá)式時(shí),其const
限定符就會(huì)丟失(請(qǐng)注意,揮發(fā)性限定符(如果存在的話)不會(huì)丟失)。
指定 const 限定類型對(duì)象的左值表達(dá)式和指定具有至少一個(gè) const 限定類型成員(包括遞歸包含的聚集或聯(lián)合成員)的struct 或 union 類型對(duì)象的左值表達(dá)式不是可修改的左值。特別是,它們不可轉(zhuǎn)讓:
const int n = 1; // object of const typen = 2; // error: the type of n is const-qualified int x = 2; // object of unqualified typeconst int* p = &x;*p = 3; // error: the type of the lvalue *p is const-qualified struct {int a; const int b; } s1 = {.b=1}, s2 = {.b=2};s1 = s2; // error: the type of s1 is unqualified, but it has a const member
const 限定結(jié)構(gòu)或聯(lián)合類型的成員獲取它所屬類型的限定條件(兩者均可在使用.
操作員或->
操作員進(jìn)行訪問時(shí)使用)。
struct s { int i; const int ci; } s;// the type of s.i is int, the type of s.ci is const intconst struct s cs;// the types of cs.i and cs.ci are both const int
如果使用 const 類型限定符(通過使用typedef)聲明數(shù)組類型,則數(shù)組類型不是 const 限定的,但其元素類型為。如果使用 const 類型限定符(通過使用typedef)聲明函數(shù)類型,則行為是未定義的。
typedef int A[2][3];const A a = {{4, 5, 6}, {7, 8, 9}}; // array of array of const intint* pi = a[0]; // Error: a[0] has type const int*
常量合格的復(fù)合文字不一定指定不同的對(duì)象; 他們可能與其他復(fù)合文字以及恰好具有相同或重疊表示的字符串文字共享存儲(chǔ)。const int * p1 =(const int []){1,2,3}; const int * p2 =(const int []){2,3,4}; // p2的值可能等于p1 + 1 bool b =“abd”==(const char []){“abc”}; // b的值可能是1 | (自C99以來) |
---|
指向非 const 類型的指針可以隱式轉(zhuǎn)換為指向相同或兼容類型的 const 限定版本的指針。逆轉(zhuǎn)換可以使用強(qiáng)制表達(dá)式來執(zhí)行。
int* p = 0;const int* cp = p; // OK: adds qualifiers (int to const int)p = cp; // Error: discards qualifiers (const int to int)p = (int*)cp; // OK: cast
請(qǐng)注意,指向指針的指針T
不能轉(zhuǎn)換為指向指針的指針const T
; 對(duì)于兩種類型的兼容,其資格必須相同。
char *p = 0;const char **cpp = &p; // Error: char* and const char* are not compatible typeschar * const *pcp = &p; // OK, adds qualifiers (char* to char*const)
任何嘗試修改類型為 const-qualified 的對(duì)象都會(huì)導(dǎo)致未定義的行為。
const int n = 1; // object of const-qualified typeint* p = (int*)&n;*p = 2; // undefined behavior
在函數(shù)聲明中,關(guān)鍵字 const 可以出現(xiàn)在用于聲明函數(shù)參數(shù)的數(shù)組類型的方括號(hào)內(nèi)。它限定了數(shù)組類型被轉(zhuǎn)換的指針類型。以下兩個(gè)聲明聲明了相同的函數(shù):void f(double xconst,const double yconst); void f(double * const x,const double * const y); | (自C99以來) |
---|
const
.
C 采用了 C ++ 的 const 限定符,但與 C ++不同,C中 const 限定類型的表達(dá)式不是常量表達(dá)式; 它們不能用作案例標(biāo)簽或初始化靜態(tài)和線程存儲(chǔ)持續(xù)時(shí)間對(duì)象,枚舉器或位域大小。當(dāng)它們用作數(shù)組大小時(shí),結(jié)果數(shù)組是 VLA。
C11 standard (ISO/IEC 9899:2011):
6.7.3 Type qualifiers (p: 121-123)
C99 standard (ISO/IEC 9899:1999):
6.7.3 Type qualifiers (p: 108-110)
C89/C90 standard (ISO/IEC 9899:1990):
3.5.3 Type qualifiers