c語言中的const的用法

2021-07-10 22:53:39 字數 1020 閱讀 7262

1)、const在前面

const int nvalue; //nvalue是const

const char *pcontent; //*pcontent是const, pcontent可變

const (char *) pcontent;//pcontent是const,*pcontent可變

char* const pcontent; //pcontent是const,*pcontent可變

const char* const pcontent; //pcontent和*pcontent都是const

2)、const在後面,與上面的宣告對等

int const nvalue; // nvalue是const

char const * pcontent;// *pcontent是const, pcontent可變

(char *) const pcontent;//pcontent是const,*pcontent可變

char* const pcontent;// pcontent是const,*pcontent可變

char const* const pcontent;// pcontent和*pcontent都是const

答案與分析:

const和指標一起使用是c語言中乙個很常見的困惑之處,在實際開發中,特別是在看別人**的時候,常常會因為這樣而不好判斷作者的意圖,下面講一下我的判斷原則:

(這個規則是錯的)(因為「()」的出現,使得這個規則有時候是不成立的。)沿著*號劃一條線,如果const位於*的左側,則const就是用來修飾指標所指向的變數,即指標指向為常量;如果const位於*的右側,const就是修飾指標本身,即指標本身是常量。你可以根據這個規則來看上面宣告的實際意義,相信定會一目了然。

另外,需要注意:對於const (char *) ; 因為char *是乙個整體,相當於乙個型別(如 char),因此,這時限定指標是const。

C語言中const的用法

1 const的普通用法 const int n 10 意思很明顯,n是乙個唯讀變數,程式不可以直接修改其值。這裡還有乙個問題需要注意,即如下使用 int a n 在ansi c中,這種寫法是錯誤的,因為陣列的大小應該是個常量,而n只是乙個變數。2 const用於指標 const int p int...

C語言中const的用法

關鍵字const用來定義常量,如果乙個變數被const修飾,那麼它的值就不能再被改變,我想一定有人有這樣的疑問,c語言中不是有 define嗎,幹嘛還要用const呢,我想事物的存在一定有它自己的道理,所以說const的存在一定有它的合理性,與預編譯指令相比,const修飾符有以下的優點 1 預編譯...

C語言中const的用法

const是c語言中的關鍵字,用來定義常變數。1 在使用const時有以下規則 const將變數變為唯讀。只有讀許可權,沒有寫許可權 資料型別對const無影響。如以下兩種定義無區別 int const a 10 不管const是在int前或後,都無影響。const int a 10 都對整形變數a...