走進const關鍵字

2021-09-29 16:27:33 字數 1495 閱讀 4689

1 #include 23

const

int x =

100;

//儲存在**區 不能修改 (全域性)

例如 const int a = 10;//全域性下   他相當於常量10,使用a和使用10沒有區別
1 const char *p 等同於char const *p --------->常量指標

const修飾*p,  *p唯讀,p可以修飾
int x =10;

int y =20;

intconst

*p =

&x;p =

&y;//可以的

*p =20;

//錯誤的

2.char * const p ------------------>指標常量

const修飾p,p唯讀,*p的內容可以修改
int x =10;

int y =20;

int*

const p =

&x;p =

&y;//錯誤的

p =20

;//可以的

3.const char* const p

p和*p都唯讀
int x =10;

int y =20;

const

int*

const p =

&x;p =

&y;//錯誤的

p =20

;//錯誤的

非指標型別

const

int a =10;

int b =20;

b = a;

//正確

a = b;

//錯誤

const int 在初始化之後,是不能再改變的。且const int 必須在宣告時就賦值。

//這種賦值是錯誤的

const

int a;

a =20

;

指標型別

1 #include

2int

main()

~~

1.修飾引數,防止在函式中意外修改實參的值

2.增加**的健壯性

3.定義常量,增加**的可讀性 例.const double pi = 3.1315926

const關鍵字用法

1 const常量 如const int max 100 優點 const常量有資料型別,而巨集常量沒有資料型別。編譯器可以對前者進行型別安全檢查,而對後者只進行字元替換,沒有型別安全檢查,並且在字元替換時可能會產生意料不到的錯誤 邊際效應 2 const修飾類的資料成員 class a const...

關鍵字const詳解

關鍵字const 1 用關鍵字const定義變數指所定義的常量。即恆定的變數,即不可改變的變數。例 const int i 10 此時 i 就是乙個整型的常量,其值不能改變。在c 中如果用const定義乙個物件,那麼物件中的成員變數就是常數,不能改變 只能為初始化的值 如果用const定義類中的成員...

const關鍵字用法

const修飾符表示該變數的值不能被改變。但得分兩種情況討論 修飾普通變數和修飾指標變數。1.普通常量 const int foo 5 表示foo不能再被賦值 foo 8 錯誤,因為foo是const修飾為不可變常量了 2.修飾指標 const char p test 表示p指向 的記憶體不可改變,...