C語言,const

來源:互聯網
上載者:User

標籤:

 

const意味著“唯讀”

ubunto下的實驗

 

1). 關鍵字const的作用是為給讀你代碼的人傳達非常有用的資訊,實際上,聲明一個參數為常量是為了告訴了使用者這個參數的應用目的。如果你曾花很多時間清理其它人留下的垃圾,你就會很快學會感謝這點多餘的資訊。(當然,懂得用const的程式員很少會留下的垃圾讓別人來清理的。)

2). 通過給最佳化器一些附加的資訊,使用關鍵字const也許能產生更緊湊的代碼。

3). 合理地使用關鍵字const可以使編譯器很自然地保護那些不希望被改變的參數,防止其被無意的代碼修改。簡而言之,這樣可以減少bug的出現。

#include <stdio.h>

void main(void)

{

 int const a = 10;

 int *p = (int*)&a;

 *p = 20;

 printf("&a=%d\n", &a);

 printf(" p=%d\n", p);

 printf(" a=%d\n", a);

 printf("*p=%d\n", *p);

}

 //&a=-1081948900

 //p=-1081948900

 //a=20

 //*p=20

 

1) 修飾一般常量 一般常量是指簡單類型的常量

const int a;

int const a;

2)修飾常指標                                                                                            const int *A  ,  int const *A; //const修飾指向的對象,A可變,A指向的對象不可變

int *const A;                  //const修飾指標A, A不可變,A指向的對象可變

const int *const A;            //指標A和A指向的對象都不可變

3) 修飾函數的常參數 const修飾符也可以修飾函數的傳遞參數,格式如下:void Fun(const int Var); 告訴編譯器Var在函數體中的無法改變,從而防止了使用者的一些無意的或錯誤的修改。

#include <stdio.h>

int const a = 10;

void main(void)

{

 int *p = (int*)&a;

 *p = 20;

 printf("%d\n", *p);

}

//段錯誤

#include <stdio.h>

void main(void)

{

 int const a = 10;

 int b = 20;

 int *p = (int*)&a;

 *p = 20;

 printf("&a=%x\n", &a);

 printf("&b=%x\n", &b);

 printf(" p=%x\n", p);

 printf(" a=%d\n", a);

 printf("*p=%d\n", *p);

}

//&a=bfbc9c1c

//&b=bfbc9c18

// p=bfbc9c1c

// a=20

//*p=20

//從中可以看出a的值存在棧中。

 

 

 

C語言,const

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.