sizeof與const關鍵字

來源:互聯網
上載者:User

 

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)

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.