输入限定符

类型限定符是描述有关类型的其他语义的关键字。它们是类型签名的组成部分。它们既可以出现在声明的最顶层(直接影响标识符),也可以出现在子级别(仅与指针相关,影响指向的值):

关键词 备注
const 防止声明对象的突变(通过出现在最顶层)或防止指向值的突变(通过出现在指针子类型旁边)。
volatile 通知编译器声明的对象(在最顶层)或指向的值(在指针子类型中)可能由于外部条件而改变其值,而不仅仅是程序控制流的结果。
restrict 优化提示,仅与指针相关。声明意图在指针的生命周期中,不会使用其他指针来访问同一个指向的对象。

关于存储类说明符(staticexternautoregister),类型修饰符(signedunsignedshortlong)和类型说明符(intchardouble 等)的类型限定符的顺序未强制执行,但是好的做法是将它们按上述顺序排列:

static const volatile unsigned long int a = 5; /* good practice */
unsigned volatile long static int const b = 5; /* bad practice */

顶级资格

/* "a" cannot be mutated by the program but can change as a result of external conditions */
const volatile int a = 5;

/* the const applies to array elements, i.e. "a[0]" cannot be mutated */    
const int arr[] = { 1, 2, 3 };

/* for the lifetime of "ptr", no other pointer could point to the same "int" object */
int *restrict ptr;

指针子类型资格

/* "s1" can be mutated, but "*s1" cannot */
const char *s1 = "Hello";

/* neither "s2" (because of top-level const) nor "*s2" can be mutated */
const char *const s2 = "World";

/* "*p" may change its value as a result of external conditions, "**p" and "p" cannot */
char *volatile *p;

/* "q", "*q" and "**q" may change their values as a result of external conditions */
volatile char *volatile *volatile q;