函数接口定义时常常遇到的是const int p或者int const p,目的让编译器帮助程序员在该函数的编写过程中不要通过p来修改p所执行的内容。如果尝试修改,编译会报错“assignment of read-only location”提示你在对一个只读区域进行赋值。原因是取值运算符的结合方向是从右到左,在左边的是对*p的修饰,说明其中的内存是const int或者int const的。
还有一种不是那么常见的定义int *const p,根据右结合性,p是const的,也就是说在后续使用p时不能对它进行修改的。如果尝试通过p=a的方式尝试把int *a传递给p,编译器会报错“assignment of read-only variable”,提示你正在对一个只读变量进行赋值操作。
#include <stdio.h>
int main(int argc, char *argv[])
{
int a[] = {10, 20, 30, 40, 50, 60};
int b[] = {1, 2, 3, 4, 5, 6};
const int *p_not_change_value = a;
int * const p_not_change_pointer = a;
int const *p_test = a;
//*p_test = 20; //fail to compile: assignment of read-only location
p_test = b;
//*p_not_change_value = 100; //fail to compile: assignment of read-only location
p_not_change_value = b;
*p_not_change_pointer = 100;
//p_not_change_pointer = b; //fail to compile: assignment of read-only variable
printf("*p_not_change_value:%d *p_not_change_pointer:%d\n", *p_not_change_value, *p_not_change_pointer);
#endif
return 0;
}