指针与const
如果指针被const修饰
- 表示一旦得到了某个变量的地址就不能再指向其他变量
- int * const q = &i; // 指针 q 是 const
- *q = 26; // OK
- q++; // Error
如果所指是const
- 表示不能通过指针修改那个变量(并不能使那个变量成为const)
- const int *p = &i;
- *p = 26; // Error
- i = 26; // OK
- p = &j; //OK
这些都是啥意思?
int i;
const int* p1 = &i;
int const* p2 = &i;
int *const p3 = &i;
- 判断哪个被const了标志是const在*的前面还是后面
- const * :所指被const了
- * const :指针被const了
转换
- 总是可以把一个非const的值转换成const的
void f(const int * x);
// const int * x; 所指被const了,表示传入的变量在这个函数中绝对不会被修改
int a = 15;
f(&a); // ok,传入一个非const值,转换为const,不能修改
const int b = a;
f(&b); // ok,传入const值,不能修改
f(const int * x){
x++; // error,const不能修改
}
- 当要传递的参数的类型比地址大的时候,这是常用的手段:既能用比较少的字节数传递值给参数,又能避免函数对外面的变量修改
const数组
- const int a[] = {1,2,3,4,5,6}
- 数组变量本身就是const指针,这里的const表明数组的每个单元都是const int
- 所以必须通过初始化进行赋值
保护数组值
- 因为把数组传入函数时传入的是地址,所以函数可以修改数组值
- 传入时用const修饰,可以保护数组值不被函数修改
- int f(const int arr[]);