限定符const
阿新 • • 發佈:2019-01-25
以前對qualifier const的理解有很大的誤區。
在 c專家程式設計中是這樣描述的:
Const Isn't
The keyword const doesn't turn a variable into a constant! A symbol with the const
qualifier merely means that the symbol cannot be used for assignment. This makes the value
read -onl y through that symbol; it does not prevent the value from being modified through
some other means internal (or even external) to the program. It is pretty much useful only
for qualifying a pointer parameter, to indicate that this function will not change the data that
argument points to, but other functions may. This is perhaps the most common use of
const in C and C++.
關鍵字const並不能將一個變數轉換成一個常量。一個帶const限定符的符號僅僅是表示這個符號不能用於賦值。也就是說這個符號的值是隻讀的;const限定符不能阻止程式通過內部或者外部方法來修改這個值。const限定符最有用之處僅僅是限定實參指標,表示這個函式將不會改變實參指標指向的資料,但其他的函式可能會。這可能實const限定符在c和c++中最普遍的用法。
1:const限定符用在資料上。
const int a = 1;
表示a是隻讀的。
2:用在指標上。
p指向一個只讀的整形變數,不可以通過*p來改變其值。p本身是個變數。
第二個const限定符限定的是p, p的值是隻讀的。
const和*的組合通常只用於模擬陣列形式引數的按值傳遞,它宣告:我給你一個指向它的指標,但你不可以改變它。
在 c專家程式設計中是這樣描述的:
Const Isn't
The keyword const doesn't turn a variable into a constant! A symbol with the const
qualifier merely means that the symbol cannot be used for assignment. This makes the value
read -onl y through that symbol; it does not prevent the value from being modified through
some other means internal (or even external) to the program. It is pretty much useful only
for qualifying a pointer parameter, to indicate that this function will not change the data that
argument points to, but other functions may. This is perhaps the most common use of
const in C and C++.
關鍵字const並不能將一個變數轉換成一個常量。一個帶const限定符的符號僅僅是表示這個符號不能用於賦值。也就是說這個符號的值是隻讀的;const限定符不能阻止程式通過內部或者外部方法來修改這個值。const限定符最有用之處僅僅是限定實參指標,表示這個函式將不會改變實參指標指向的資料,但其他的函式可能會。這可能實const限定符在c和c++中最普遍的用法。
1:const限定符用在資料上。
const int a = 1;
表示a是隻讀的。
2:用在指標上。
- cosnt int *p;
p指向一個只讀的整形變數,不可以通過*p來改變其值。p本身是個變數。
- int const *p; 與上面的是等價的。
- int * const p = &variable;
- const int *cosnt p = &variable;
第二個const限定符限定的是p, p的值是隻讀的。
const和*的組合通常只用於模擬陣列形式引數的按值傳遞,它宣告:我給你一個指向它的指標,但你不可以改變它。