1.常量指针(const * ),红色标记不可修改
#include <iostream> using namespace std; int main(){ int a = 20; int b = 10; const int * p = &a;//指针的指向可以修改,但是指针指向的值不可改, //*p = 20; //错误,表达式必须是可修改的左值 //cout << "a = " << a << endl; p = &b; cout << "*p = " << *p << endl; return 0; }
2.指针常量 ( * const)
#include <iostream> using namespace std; int main(){ int a = 10; int b = 10; int * const p = &a; //指针指向不可以改,指针指向的值可以改 *p = 20; cout << "a = " << a << endl; //p = & b; //错误,表达式必须是可修改的左值 //cout << "b = " << b << endl; return 0; }
3.const 既修饰指针又修饰常量 (const * const p)
#include <iostream> using namespace std; int main(){ int a = 10 ; int b = 5; //指针的指向和指针指向的值都不可以修改 const int * const p = &a; //*p = 20; //错误 //cout << "a = " << a << endl; //p = &b; //错误 //cout << "b = " << b << endl; return 0; }