C/C++中的const int*和int * const
代码:
1 #include <iostream> 2 3 using namespace std; 4 5 int main(){ 6 const int *p; 7 int a = 2; 8 p = &a; 9 a = 5; 10 11 cout<<p<<" "<<*p<<endl; 12 13 int b = 10; 14 p = &b; 15 16 cout<<p<<" "<<*p<<endl; 17 18 //*p = 1; 错误,不允许修改,*p是常量 19 //cout<<*p<<endl; 20 21 int * const p1 = &a;//此处必须初始化,否则编译错误 22 cout<<p1<<" "<<*p1<<endl; 23 24 //p1 = &b; 错误,不允许向常量指针赋值 25 //cout<<p1<<" "<<*p1<<endl; 26 27 const int * const p2 = &a; 28 cout<<p2<<" "<<*p2<<endl; 29 a = 100; 30 cout<<p2<<" "<<*p2<<endl; 31 //*p2 = 290; 32 //p2 = &b; 两者都不允许 33 34 return 0; 35 }
输出:
0x7ffe6a0ecc34 5 0x7ffe6a0ecc30 10 0x7ffe6a0ecc34 5 0x7ffe6a0ecc34 5 0x7ffe6a0ecc34 100
需要注意的是const int是可以修改的,见以下代码:
1 int main(){ 2 3 const int i = 0; 4 int *j = (int*)&i; 5 *j = 1; 6 cout<<i<<" "<<*j<<endl; 7 8 return 0; 9 }
输出:
0 1