const在*的左邊,則指針指向的變量的值不可直接通過指針改變(可以通過其他途徑改變);在*的右邊,則指針的指向不可變。簡記爲"左定值,右定向"。
①const int p;
②const int* p;
③int const* p;
④int * const p;
⑤const int * const p;
⑥int const * const p;
第一種是常量整數,沒什麼好說的。
後面五種是指針,有一個簡便的辦法記憶。
從右往左讀,遇到p就替換成“p is a ”遇到*就替換成“point to”。
比如說②,讀作:p is a point to int const.
p是一個指向整型常量的指針。
③讀作:p is a point to const int.
意思跟②相同。
④讀作:p is a const point to int.
p是一個常量指針,指向整型。
⑤讀作:p is a const point to int const.
⑥讀作:p is a const point to const int.
⑤和⑥的意思相同,p都是常量指針,指向整型常量。