3. const修饰指针
const修饰指针时,可以限制指针本身或指针指向的内容的修改。根据const的位置,有以下几种情况:
(1)const修饰指针指向的内容
表示指针指向的内容不能被修改,但指针本身可以修改。
int x = 10;
const int *ptr = &x; // ptr指向的内容不能被修改
// *ptr = 20; // 错误:ptr指向的内容是常量
ptr = NULL; // 正确:ptr本身可以修改
(2)const修饰指针本身
表示指针本身不能被修改,但指针指向的内容可以修改。
int x = 10;
int *const ptr = &x; // ptr本身不能被修改
*ptr = 20; // 正确:ptr指向的内容可以修改
// ptr = NULL; // 错误:ptr本身是常量
(3)const修饰指针本身和指针指向的内容
表示指针本身和指针指向的内容都不能被修改。
int x = 10;
const int *const ptr = &x; // ptr本身和ptr指向的内容都不能被修改
// *ptr = 20; // 错误:ptr指向的内容是常量
// ptr = NULL; // 错误:ptr本身是常量
作用:限制指针的修改权限,增加代码的安全性。
使用场景:常用于传递不希望被修改的指针或数组。
4. const修饰函数返回值
当const用于修饰函数返回值时,表示返回的值不能被修改。
示例:
const int getConstantValue() {
return 42;
}
int main() {
const int value = getConstantValue();
// value = 10; // 错误:value是常量,不能修改
return 0;
}
作用:确保返回的值在调用者处不能被修改。
使用场景:通常用于返回常量值或常量指针。
5. const修饰数组
当const用于修饰数组时,表示数组的内容不能被修改。
示例:
<p>const int arr[] = {1, 2, 3, 4};</p><p>// arr[0] = 10; // 错误:arr是常量数组,不能修改</p>
作用:确保数组的内容在初始化后不能被修改。
使用场景:通常用于定义常量数组。
|