的const
,volatile
和restrict
(C99起)关键字都被认为类型限定符。它们是类型签名不可分割的组成部分,并描述了有关类型的附加语义。
如果它们出现在一个声明的最上层,它们会影响声明标识符:
const int a = 5; // prevents modifications of "a"
int *const p = &x; // prevents modifications of "p", but not "*p"
int **const q = &y; // prevents modifications of "q", but not "*q" and "**q"
如果它们出现在指针亚型(星号之前),因为它们影响到指向的在特定值提领的水平:
const int *p = &x; // prevents modifications of "*p", but not "p"
const int **q = &y; // prevents modifications of "**q", but not "*q" and "q"
const int *const *r = &z; // prevents modifications of "**r" and "*r", but not "r"
const int *const *const s = &a; // prevents modifications of "**s", "*s" and "s"
的维基百科摘录讨论了声明指针两种不同的约定:
int *p; // more common in C programming
int* p; // more common in C++ programming
我会说“真”约定是第一个,因为它根据语言的语法(声明镜像使用)工作。该声明中的星号实际上是与正常表达式中的指针相同的解引用操作符。因此,在p
(指针本身)上应用*
(间接)后,返回int
类型。
还要注意的是类型限定符相对于排序,以类型说明符和其他类型的预选赛没有关系,所以这些声明是等价的:
const int a; // preferred
int const a; // same, not preferred
const volatile int b; // preferred
volatile const int b; // same, not preferred
volatile int const b; // same, not preferred
const int *p; // preferred
int const *p; // same, not preferred
该链接并不会导致任何地方有用。 – molbdnilo
我只是修复了这个链接。 –
该wikipedia部分感到困惑。如果例子是'const int * ptrToConst;'和'const int * const constPtrToConst;' – user3386109