2011-07-06 63 views
12

我無法找到C和C++語言中聲明中使用const的方式的直觀模式。下面是一些例子:瞭解「const」在聲明中的位置

const int a; //Const integer 
int const a; //Const integer 
const int * a; //Pointer to constant integer 
int * const a; //Const pointer to an integer 
int const * a const; //Const pointer to a const integer 

在1,2線,似乎const來臨之前或之後int,這是它修改。

  1. 那麼如何,在第4行,該編譯器決定const正在修改*(指針),而不是int
  2. 編譯器遵循什麼規則來決定const適用於哪個事物?
  3. 它是否遵循相同的規則*
+9

強制性鏈接到[順時針螺旋規則](http://c-faq.com/decl/spiral.anderson.html) –

+1

如果沒有涉及數組或函數,只需**從右向左讀* *也可以提供幫助:'int const * const a':''a'是一個const const指針「。 –

+0

馬克,如果您提交了答案,我會檢查它。非常有用,真的幫我弄明白了! –

回答

4

編譯器通常從右到左,所以讀取類型:

T const& const 

會被讀作:

const (a constant) 
& (to a reference) 
const (to a constant) 
T (of type T) 

所以,基本上關鍵字「const」修改它之前的所有內容。然而,存在的情況下的例外,其中「常量」至上,在這種情況下,它直接地修改項到它的右邊:

const T& const 

以上讀作:

const (a constant) 
& (to a reference) 
const T (to a constant of type T) 

並且以上相當於const const & const。雖然這是編譯器如何做的,但我真的只是推薦記住「T」,「const T」,「const T &」,「const T *」,「const T & const」,「const T * const「,」T & const「和」T * const「。你很少會遇到任何其他的「const」變體,當你這樣做時,使用typedef可能是個好主意。

+0

感謝您解釋編譯器是如何做到這一點的,而不僅僅是「一個人能做到這一點」,而這正是我所要求的。 –

+5

我相信沒有像「不變的參考」這樣的東西(換句話說,它們總是不變的)。所以'T&const'在語義上是不正確的。 VC++ 2010發出警告並忽略'const'。只是提醒。 :) – Nubcase

+1

-1爲壞榜樣。你應該在這裏使用一個指針,而不是引用。 –

7

假設你始終把const類型的權,你可以讀一個變量聲明爲從右一個句子到左:

int const x;  // x is a constant int 
int *const x;  // x is a constant pointer to an int 
int const *x;  // x is a pointer to a constant int 
int const *const x; // x is a constant pointer to a constant int 

如果你把const到這仍然有效一種類型的左側,但需要更多的精力。需要注意的是這個工作同樣出色的指針到指針(和高階結構):

int *const *const x; // x is a constant pointer to a constant pointer to an int 
+0

以30秒擊敗我! –

+1

所以基本規則是從右到左讀的,如果最左邊的東西是'const',那麼它就直接適用於它的右邊。所以'const'適用於左邊的東西,除非左邊沒有東西,所以它適用於右邊的東西。 –

2

對於指針,這裏是我從斯科特邁爾斯的一本書(我認爲)中挑選出來的一個。通過*繪製垂直線,然後與const關鍵字相同的那一行是const。

澄清:

int * const a意味着一個是常量,而不是INT。而「a」是一個指向(非const)int的指針。

0

好了,開始掉,這個問題更多的是一種個人喜好。對於休閒程序員來說,這更像是一種個人風格。然而,對於那些與企業打交道的人來說,可以有一些他們爲程序員設計的編碼慣例,以便每個人都可以使用一致的編碼風格。

(1)const的int * const a;這意味着你不能改變你的指針指向,但你可以修改存儲位置。 (2)'const'由你作爲程序員決定,你是否希望指針指向的地址是常量,或者如果你希望指針不修改它指向的指針。

(3)是該規則是相同的*如在const int * const a;

的情況下,作爲附加的註釋,你的最後一行是無效的C89。

希望它有幫助。乾杯!

+0

這對程序員來說可能是一種偏好,但絕對不適合其他必須閱讀他的代碼的人! –

+0

這個問題不僅僅是寫在他們身上,還要讀別人寫的。 –

+0

同意。乾杯! :) – Vern

1

理解這些的關鍵是要認識到*綁定到a,而不是類型。所以你應該閱讀這些:

const int a; // a has type const int 
int const a; // a has type int const 
const int * a; // *a has type const int 
int * const a; // *(const a) has type int, which means *a has type int and a is const 
int const * a const; // *(const a) has type int const, which means *a has type const int and a is const. 

(請注意雖然C++引用不遵循此規則)。