最近学校的花开了,选了一张三号楼窗前的白玉兰,(#^.^#)
1.修饰普通变量
当 const
用于修饰普通变量时,该变量的值在初始化之后就不能再改变。
#include <stdio.h>int main() {const int num = 10;// num = 20; // 错误,不能修改常量的值printf("num 的值是: %d\n", num);return 0;
}
2.修饰数组
const修饰数组时,数组元素的值不能够被修改
#include <stdio.h>int main() {const int arr[3] = {1, 2, 3};// arr[0] = 10; // 错误,不能修改常量数组元素的值for (int i = 0; i < 3; i++) {printf("%d ", arr[i]);}printf("\n");return 0;
}
3.修饰指针
3.1 常量指针
指针指向的内容不能被修改,但指针本身可以指向其他地方。
#include <stdio.h>int main() {int num1 = 10;int num2 = 20;const int *ptr = &num1;// *ptr = 30; // 错误,不能通过指针修改指向的内容ptr = &num2; // 正确,指针可以指向其他地方printf("ptr 指向的值是: %d\n", *ptr);return 0;
}
在这个例子里,ptr
是一个常量指针,不能通过 *ptr
来修改其指向的值,但可以让 ptr
指向其他变量。
3.2 指针常量
指针本身的值不能被修改,但可以修改指针指向的内容。
#include <stdio.h>int main() {int num1 = 10;int num2 = 20;int *const ptr = &num1;*ptr = 30; // 正确,可以修改指针指向的内容// ptr = &num2; // 错误,不能修改指针本身的值printf("ptr 指向的值是: %d\n", *ptr);return 0;
}
在这段代码中,ptr
是一个指针常量,不能让 ptr
指向其他变量,但可以通过 *ptr
修改其指向的值。
4.修饰函数参数
在函数参数中使用 const
,可以防止函数内部修改传入的参数值
#include <stdio.h>void printValue(const int num) {// num = 20; // 错误,不能修改常量参数的值printf("传入的值是: %d\n", num);
}int main() {int num = 10;printValue(num);return 0;
}
这里,printValue
函数的参数 num
被 const
修饰,在函数内部无法修改 num
的值。
5.修饰函数返回值
使用 const
修饰函数返回值,可让返回值成为只读的
#include <stdio.h>const int getValue() {return 10;
}int main() {const int result = getValue();// result = 20; // 错误,不能修改常量的值printf("返回的值是: %d\n", result);return 0;
}
在这个例子中,getValue
函数返回一个 const
类型的值,将其赋给 result
后,不能再对 result
进行修改。