C++中sizeof與const關鍵字會經常出錯。
一、sizeof
在32位系統中下面各個sizeof的值是多少?
int *p = NULL;sizeof(p)//值為4, 因為32位系統中的指標佔4位元組sizeof(*p)//4, 因為此指標指向的是int類型int a[100];sizeof(a)//400, 數組大小sizeof(a[100])//4, 訪問元素, 相當於指標sizeof(&a)//400, 數組別名sizeof(&a[0])//4, 訪問元素int b[100];void fun(int b[100]){sizeof(b);//4, 這裡不再是整個數組的大小,b蛻變成一個指標}
二、const
const修飾的值是常量,確切的說應該是唯讀變數。其值在編譯時間不能被使用,因為編譯器在編譯時間不知道其儲存的內容。
當const修飾指標的時候,要注意一些情況,例如下面的情況:
const int *p;//p可變, p指向的對象不可變int const *p;//p可變, p指向的對象不可變int * const p;//p不可變, p指向的對象可變const int *const p;//指標p和p所指向的對象都不可變
int const * p 和int * const p是一致的,所以只要看const右邊的是什麼就可以判斷了
int const * p 中const右邊是*p 所以p是一個指標常量
int* const p 中const右邊是p,所以這個變數是常量,這個變數是指標,所以這個也是指標常量
const int* p 中const右邊是int,所以這個整型是常量,所以說這個*p的值不能改變;
對於上面的東西很難記住,可以先忽略類型名,看const離哪一個近,離誰近就修飾誰
const int *p; //const修飾 *p, 所以p指向的對象不可變
int const *p; //const修飾 *p, 所以p指向的對象不可變
int * const p; //const修飾p, p不可變, p指向的對象可變
constint *const p; //前一個const修飾*p, 後一個修飾p, 所以p和*p都不可變
另外,const也可以修飾函數的參數。當不希望這個參數值在函數體內被意外改變時使用。例如:
void Fun(const int i)
這就告訴了編譯器,在函數體中,i 不能被改變。
const還可以修飾函數的傳回值,則傳回值不能被修改,例如:
const int Fun(void)