1. const int *ptr = NULL; <=> int const *ptr = NULL;指針
1) 表示指向符號常量的指針變量,指針變量自己並不是const因此能夠指向其餘變量。變量
2) const 的做用能夠看做是「禁止經過*ptr"來改變被ptr指向的變量的值,但被指向的變量 其自己可否改變須要看其定義。技巧
eg: const int i = 1, int j = 2;error
ptr = &i; // okco
*ptr = 27 // errorconst
i = 2 // error i is const
ptr = &j; // ok
*ptr = 28; // error
j = 3; // ok
2. const int *ptr vs int * const ptr;
1) 要區分以上兩種形式重點看const與*的相對位置:
const在*以前表示」指向符號常量的指針「
const在*以後表示」指向int類型變量的常量指針「
注意:若聲明成 int * const ptr = NULL;則ptr的值不可改即不可再指向其它變量,
但能夠經過*ptr修改其指向的變量(若是指向了的話)。
2)識記技巧
看const修飾的是*ptr仍是ptr?
當 const 在 * 以前能夠認爲 const修飾的是 *ptr,此時*ptr的」值「不可變,ptr的值可變
當 const 在 * 以後能夠認爲 const修飾的是 ptr,此時ptr的值不可變,*ptr的值可變
const修飾誰,誰的值就不可再變。
3. const int * const ptr;
1) 表示」指向int型符號常量的常量指針「
2) const 即修飾了 *ptr 表示不可經過*ptr修改其指向變量的值
又修飾了 ptr 表示ptr中的值不可再修改即不能再指向其餘變量