const 修饰指针的问题
判断法则
沿着*
号划一条线:
- 如果const位于
*
的左侧,则const就是用来修饰指针所指向的变量,即指针指向为常量 - 如果const位于
*
的右侧,const就是修饰指针本身,即指针本身是常量
验证
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 1;
int b = 2;
/*const int XX 与 int const XX 等价*/
const int* p1 = &a;
printf("%d",*p1);
//*p1 += 1; ERROR const此时修饰指向的内容,无法修改常量
p1 = &b;// OK const 此时不修改指针,故指针本身值可变
int const *p2 = &b;
//*p2 += 1; ERROR 无法修改常量
p2 = &a; //OK const 此时不修改指针,故指针本身值可变
/*const 修饰指针本身*/
int* const p3 = &a;
*p3 += 1; // OK p3本身是常量不可变,但是可以修改所执行的内容
//p3 = &b; ERROR 无法修改p3本身,因为p3本身是常量
const int* const p4 = &b;
//*p4 += 1; ERROR 指向的内容被修饰为常量
//p4 = &a; ERROR 指针本身值也被修饰为常量
//const (int*) p = &a; syntax error
//(int*) const p = &b; syntax error
return EXIT_SUCCESS;
}