?
Ce document utilise Manuel du site Web PHP chinois Libérer
C 類型系統(tǒng)中的每個單獨類型都具有該類型的多個限定版本,對應于 const,volatile 中的一個,兩個或全部三個,并且對于指向對象類型的指針,限制限定符。該頁面描述了 const 限定符的影響。
用 const 限定類型聲明的對象可能被編譯器放置在只讀存儲器中,如果程序中永遠不會獲取const對象的地址,它可能根本就不存儲。
const
語義僅適用于左值表達式; 每當在不需要左值的上下文中使用常量左值表達式時,其const
限定符就會丟失(請注意,揮發(fā)性限定符(如果存在的話)不會丟失)。
指定 const 限定類型對象的左值表達式和指定具有至少一個 const 限定類型成員(包括遞歸包含的聚集或聯合成員)的struct 或 union 類型對象的左值表達式不是可修改的左值。特別是,它們不可轉讓:
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 限定結構或聯合類型的成員獲取它所屬類型的限定條件(兩者均可在使用.
操作員或->
操作員進行訪問時使用)。
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)聲明數組類型,則數組類型不是 const 限定的,但其元素類型為。如果使用 const 類型限定符(通過使用typedef)聲明函數類型,則行為是未定義的。
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*
常量合格的復合文字不一定指定不同的對象; 他們可能與其他復合文字以及恰好具有相同或重疊表示的字符串文字共享存儲。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 類型的指針可以隱式轉換為指向相同或兼容類型的 const 限定版本的指針。逆轉換可以使用強制表達式來執(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
請注意,指向指針的指針T
不能轉換為指向指針的指針const T
; 對于兩種類型的兼容,其資格必須相同。
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 的對象都會導致未定義的行為。
const int n = 1; // object of const-qualified typeint* p = (int*)&n;*p = 2; // undefined behavior
在函數聲明中,關鍵字 const 可以出現在用于聲明函數參數的數組類型的方括號內。它限定了數組類型被轉換的指針類型。以下兩個聲明聲明了相同的函數:void f(double xconst,const double yconst); void f(double * const x,const double * const y); | (自C99以來) |
---|
const
.
C 采用了 C ++ 的 const 限定符,但與 C ++不同,C中 const 限定類型的表達式不是常量表達式; 它們不能用作案例標簽或初始化靜態(tài)和線程存儲持續(xù)時間對象,枚舉器或位域大小。當它們用作數組大小時,結果數組是 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