Try   HackMD

C++ CV Qualifiers

const

int x = 5; const int y = 10;

變數 y 是一般變數它是可以任意被修改的;而變數 x 是常數,它則不可以被修改。

const int x; // uninitialized 'const x'

使用 const 宣告時一定要初始化。

const int* p = &x; const int* q = &y; int* r = &y; // error: invalid conversion from 'const int*' to `int*`

我們先來看第一行,const int* 指標指向 int,所以原先的變數 x 是可以被修改,但如果你透過指標來存取該變數的話,就不能修改其變數了,因為它是 const
第二行的部分是,const int* 指標指向 const int,就蠻合情合理沒太多問題。
第三行的話則編譯不會通過,因為賦予指標 r 所指向的變數 y 是一個 const int,本來變數就不可以修改了,你卻想要用一個可以修改的指標來指向它,那就矛盾不合理,這邊編譯器就不讓你通過了。

const int x = 5; const int y = 10; const int* p = &y; const int* const q = &y; p = &x; q = &x; // error: assignment of read-only variable 'q'

嘿嘿,開始要搞混了。你一定在思考這到底是三小。有一個招數,你從右往左讀,const 修飾的是左邊的東西,那如果左邊沒東西才往右邊修飾。所以 const int* const 意思是:除了我指標所指向的變數不能修改之外,我指標自己本身也不能修改(永遠只能指向同一個變數了)。

west const vs east const

// west const 寫法 const int x = 5; const int* const p = &y; // east const 寫法 int const x = 5; int const * const p = &y;

有興趣可以參考這個

constexpr

https://stackoverflow.com/questions/13346879/const-vs-constexpr-on-variables
https://tjsw.medium.com/潮-c-constexpr-ac1bb2bdc5e2
https://www.zhihu.com/question/35614219

tags: C++