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



