const:修饰数据类型,意义:只读。
使用地方:数据类型前面,数据类型后面。
示例:
int number = 10; //变量
const int number = 10; //number是只读的,并且number的值永远为10
局部变量:const int number; //number的值为随机数(内存);不能被修改了
int const number = 10; //number是只读的,并且number的值永远为10
int const number[3] = {10};
//number[3]是只读的,并且number[0]的值永远为10,number[1]的值永远为0,number[2]的值永远为0
const int number[3] = {10};
//number[3]是只读的,并且number[0]的值永远为10,number[1]的值永远为0,number[2]的值永远为0
const int * pnumber = &number;//地址中的内容是只读的,地址可以修改
int * const pnumber = &number;//地址是只读的,地址的内容是可以修改的。
int main(void) { int number = 10; const int *pnumber = &number; *pnumber = 100;//error:assignment of read-only location '*pnumber' number=100;//可以编译通过,指针去取值也是100 printf("*pnumber = %d\r\n", *pnumber); return 0; }
int main(void) { int number = 10; int count = 200; int *const pnumber = &number; pnumber=&count;//error:assignment of read-only variable 'pnumber' printf("*pnumber = %d\r\n", *pnumber); return 0; }