const int * ,int const * 以及 int * const 的区别
const int * p; //保护p内容,常量的 int类型指针p
int const * p; //保护p内容,int类型的 常量指针p
int * const p; //保护p地址,int类型的 指针常量p
const在*的左边,保护内容
const在*的右边,保护地址
由于保护地址,所以在初始化的时候就需要给定地址,不然后面没法修改了。
#include <iostream>
using namespace std;
int main()
{
int i = 10;
int j = 20;
int * const p = &i;//一定要初始化
p = &j;//p就是一个常量,所以不能给p赋值,此处报错
return 0;
}
#include <iostream>
using namespace std;
int main()
{
const int * p;//未初始化
int i = 10;
p = &i;
*p=20; //此处报错
printf(" p = %d \n",*p);
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int const * p;//未初始化
int i = 10;
p = &i;
*p=20; //此处报错
printf(" p = %d \n",*p);
return 0;
}