按英文的字面意思,從右向左理解就比較清楚了:
const char *pointer
常量指標(底層const):pointer to const
字面意思:指向常量的指標,不能通過這個指標修改指向的內容
char *const pointer
指標常量(頂層const):const pointer
字面意思:指標本身是個常量,不能修改這個指標的指向
看一段**:
char hello[6] = "hello";
char world[6] = "
world";
const
char *p2const = hello; //
pointer to const
char *const constp = hello; //
const pointer
p2const = world; //
value of p2const is "world"
//constp = world;
//constant pointer cannot be reassigned
constp[
0] = '
y'; //
value of constp is "yello"
//p2const[0] = 'y';
//pointer to constant, cannot change the value
cout
<< p2const << '
'<< constp << endl; //
"world yello"
! 注:c++中 auto 型別推斷會忽略頂層const,保留底層const。如果設定為 auto& auto的引用時,頂層const性質保留
C 常量 const和readonly
c 常量主要分為兩種 編譯時和執行時常量 編譯時常量用關鍵字const來定義,執行時常量用關鍵字readonly來定義 兩者區別 編譯時常量...
C 常量 const和readonly 2
對於執行時常量,只能在初始化時賦值,或者是建構函式中複製。而不能在其他地方賦值,否則會提示錯誤。 還是用上篇的例子,在limitations...
C 中指標常量和常量指標的區別
在c 學習使用過程中,每個人都不可避免地使用指標,而且都或多或少的接觸過常量指標或指標常量,但是對這兩個的概念還是很容易搞糊塗的。 本文即是...