首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

const type qualifier

C 类型系统中的每个单独类型都具有该类型的多个限定版本,对应于 const,volatile 中的一个,两个或全部三个,并且对于指向对象类型的指针,限制限定符。该页面描述了 const 限定符的影响。

用 const 限定类型声明的对象可能被编译器放置在只读存储器中,如果程序中永远不会获取const对象的地址,它可能根本就不存储。

const语义仅适用于左值表达式; 每当在不需要左值的上下文中使用常量左值表达式时,其const限定符就会丢失(请注意,挥发性限定符(如果存在的话)不会丢失)。

指定 const 限定类型对象的左值表达式和指定具有至少一个 const 限定类型成员(包括递归包含的聚集或联合成员)的struct 或 union 类型对象的左值表达式不是可修改的左值。特别是,它们不可转让:

代码语言:javascript
复制
const int n = 1; // object of const type
n = 2; // error: the type of n is const-qualified
 
int x = 2; // object of unqualified type
const 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 限定结构或联合类型的成员获取它所属类型的限定条件(两者均可在使用.操作员或->操作员进行访问时使用)。

代码语言:javascript
复制
struct s { int i; const int ci; } s;
// the type of s.i is int, the type of s.ci is const int
const struct s cs;
// the types of cs.i and cs.ci are both const int

如果使用 const 类型限定符(通过使用typedef)声明数组类型,则数组类型不是 const 限定的,但其元素类型为。如果使用 const 类型限定符(通过使用typedef)声明函数类型,则行为是未定义的。

代码语言:javascript
复制
typedef int A[2][3];
const A a = {{4, 5, 6}, {7, 8, 9}}; // array of array of const int
int* 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 限定版本的指针。逆转换可以使用强制表达式来执行。

代码语言:javascript
复制
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; 对于两种类型的兼容,其资格必须相同。

代码语言:javascript
复制
char *p = 0;
const char **cpp = &p; // Error: char* and const char* are not compatible types
char * const *pcp = &p; // OK, adds qualifiers (char* to char*const)

任何尝试修改类型为 const-qualified 的对象都会导致未定义的行为。

代码语言:javascript
复制
const int n = 1; // object of const-qualified type
int* 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以来)

关键词

笔记

C 采用了 C ++ 的 const 限定符,但与 C ++不同,C中 const 限定类型的表达式不是常量表达式; 它们不能用作案例标签或初始化静态和线程存储持续时间对象,枚举器或位域大小。当它们用作数组大小时,结果数组是 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

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com