1.用指针直接修改 int num 的值,不会报错
#include <stdio.h>
int main() {
int num = 10;
int* p = #
*p = 20;
printf("%d\n", num);
return 0;
}
20
2.用指针直接修改 const int num 的值,会有警告
#include <stdio.h>
int main() {
const int num = 10;
int* p = #
*p = 20;
printf("%d\n", num);
return 0;
}
temp.c: In function ‘main’: temp.c:10:14: warning: initialization discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] int* p = # ^ 20
3.const 放在指针变量的左边时,修饰的是p,即:不能通过p来改变p(num)值,const 放在指针变量的右边时,修饰的是指针变量p本身,p不能被改变
#include <stdio.h>
int main() {
const int num = 10;
int n = 100;
const int* const p = #
*p = 20;
p = &n;
printf("%d\n", num);
return 0;
}
此时,下面两个语句都会报错
*p = 20; p = &n;
|