const修饰指针有三种情况:
1.const修饰指针——常量指针;
2.const修饰常量——指针常量;
3.const既修饰指针,又修饰常量;
一. const修饰指针——常量指针: const int *p=&a;
特点:常量指针的指向可以修改,但指针指向的值不可以改;
#include<iostream>
using namespace std;
int main(){
int a=10;
int b=20;
const int*p=&a;
cout<<"*p="<<*p<<endl;
cout<<"p="<<p<<endl;
// *p=30; //错误,因为常量指针中,指针指向的值不可以改;
p=&b;//正确,常量指针中,指针的指向可以修改;
return 0;
cout<<"*p="<<*p<<endl;
cout<<"p="<<p<<endl;
}
二. const修饰常量 ——指针常量 int * const p=&a;
特点:常量指针指向的值可以修改,但指针的指向不可以改;
三.const 既修饰指针,又修饰常量
特点:指针的指向何指针指向的值都不可以修改;
//记忆的技巧: 看符号得出名字 例:const int *p 中const在前,*在后,所以直译: 常量指针;
同理,int * const p 中 *在前 const在后 所以:指针常量;
记忆使用: 修饰紧跟着的符号, const int *p 中 const 后紧跟着*,所以*p就不能修改,
int * const p 中 const 后紧跟着p ,所以p就不能修改;
即: