的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