const修饰指针和const修饰常量
常量指针(const修饰指针)
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
const int *p = &a;
cout << *p <<endl;
*p = 20; // 错误,值不可以改变
p = &b; //正确,指向可以改变
return 0;
}
指针常量(const修饰常量)
#include <iostream>
using namespace std;
int main()
{
int a = 10, b = 20;
int *const p = &a;
p = &b; //错误,指向不可以改变
*p = 520; //正确,值可以改变
*p = b; //正确,值可以改变
return 0;
}
const修饰指针和const修饰常量
都不可改变!!!
#include <iostream>
using namespace std;
int main()
{
int a = 10, b = 20;
const int *const p = &a;
p = &b; //错误,指向和值都不可以改变
*p = 520; //错误,指向和值都不可以改变
*p = b; //错误,指向和值都不可以改变
return 0;
}
总结(省流小助手):
1、当const修饰指针
时,指针指向可以修改
,指向的值不可以修改
2、当const修饰常量
时,指针指向不可以修改
,指向的值可以修改
3、当const修饰指针和常量
时,指针指向和指针指向的值都不可以修改