const char

const char

introduction

  • Read the pointer declarations right-to-left.
  • const 放在 type 前或後是相同的
    • const char * const * is the same as char const * const *: a (non-const) pointer to a const pointer to a const char.
    • const char * is the same as char const *: a (non-const) pointer to a const char.
    • const char * * is the same as char const * *: a (non-const) pointer to a (non-const) pointer to a const char.

      brief

  • const X* p means “p points to an X that is const“: the X object can’t be changed via p.
  • X* const p means “p is a const pointer to an X that is non-const“: you can’t change the pointer p itself, but you can change the X object via p.
  • const X* const p means “p is a const pointer to an X that is const“: you can’t change the pointer p itself, nor can you change the X object via p.

const char* ptr; char const * ptr;

  • 定義一個指向字元常量的指標
  • ptr是一個指向 char* 型別的常量,所以不能用ptr來修改所指向的內容,換句話說,*ptr的值為const,不能修改
    • 但是ptr的宣告並不意味著它指向的值實際上就是一個常量,而只是意味著對ptr而言,這個值是常量
    • 實驗如下:ptr指向str,而str不是const,可以直接通過str變數來修改str的值,但是確不能通過ptr指標來修改。

char* const ptr;

  • 定義一個指向字元的指標常數,即const指標
  • 實驗得知,不能修改ptr指標,但是可以修改該指標指向的內容。

reference