最近复习C,看到指针。记录一下这个const的用法。
测试代码:
#include <stdio.h>
int main() {
int a = 100, b = 200;
const int *p = &a;
int * const q = &b;
printf("a=%d, *p=%d\n", a, *p);
printf("b=%d, *q=%d\n", b, *q);
p = &b;
//q = &a;
printf("*p = %d\n", *p);
//*p = b;
*q = 888;
printf("*q = %d\n", *q);
return 0;
}
测试结果:
a=100, *p=100
b=200, *q=200
*p = 200
*q = 888
解释如下:
const int *p = &a;
此句,因为const写在int *的前面,表示不可以利用p指针间接改变a变量值,如: *p = 1,但是可以改变p指针指向另一个变量,如: p = &b。
int * const q = &b;
此句,因为const写在q的前面,表示不可以指定另一个变量的地址给q指针,如: q = &a,但是可以改变*q的值,如: *q = 2。
要是有如下语句:
const int * const p = &a;
表示不能通过*p间接改变变量a的值,也不能再指定另一个变量的地址给p指针。
要是放开上面代码中的两个注释,编译的时候报错:
../test.c: In function ‘main’:
../test.c:21: error: assignment of read-only variable ‘q’
../test.c:24: error: assignment of read-only location