C與C++基礎--const與基礎數據類型

C與C++基礎–數組指針與指針數組
C與C++基礎–結構體struct和typedef struct 區別
C與C++基礎–函數
C與C++基礎–內存管理

const 是 constant 的縮寫,本意是不變的,不易改變的意思。在 C++ 中是用來修飾內置類型變量,自定義對象,成員函數,返回值,函數參數。

C++ const 允許指定一個語義約束,編譯器會強制實施這個約束,允許程序員告訴編譯器某值是保持不變的。如果在編程中確實有某個值保持不變,就應該明確使用const,這樣可以獲得編譯器的幫助。

有時候看定義總是一頭霧水,我們上圖與代碼來分析

變量+const變成常量

當我們定義一個變量x = 3的時候變量名是x,存儲地址是&x ,存儲內容是3.

int x = 3; 

在這裏插入圖片描述
當我們定義一個變量x = 3 前面加上const的時候就變成來一個常量,常量名是x,存儲地址是&x ,存儲內容是3.

const int x = 3; 

類似與 #define x = 3;

const與指針類型

const int *p = NULL;
int const *p = NULL;

這倆貨是一個意思

const int * const p = NULL;
int const * const p = NULL;

這倆貨也是一個意思

例子一:

int y = 4;
int x = 3;
const int *p = &x;
p = &y;//可以的
*p = 4;//錯誤的

結論: const int * p = &x;
const 修飾的是int這個值不能改變,但是指針p是可以改變的

例子二:

int y = 4;
int x = 3;
int *const p = &x;
p = &y;//錯誤的

結論:nt *const p = &x;
這裏的const是修飾的指針p,指針p一旦被賦值就不能再修改。

例子三:

int y = 4;
int x = 3;
const int *const p = &x;
p = &y;//錯誤的
*p = 4;//也是錯誤的

結論:const int *const p = &x;
這裏const修飾來指針也修飾了int,這裏一旦被賦值,指針不能變,*p也不能變

const 與引用

例子一

int x  = 3;
const int &y = x;
x = 20;
//y = 20; 錯誤的

一下關於const的寫法:

const int x = 3; x = 5;  ❌

int x = 3; const int y = x; y = 5; ❌

int x = 3; const int *y = &x; *y = 5; ❌

int x =3,z=4; int * const y = &x; y = &z;❌

const int x = 3; const int &y =x; y =5;❌

const int x = 3; int * y = &x; ❌ //這個爲什麼錯呢 因爲前面不可變,後面可變所以又風險。

int x = 3; const int 8y = &x; //這個與上面對比這個是對的,前面可變,後面不可變是可以的
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章