const与指针

const int a;
int const a;

常量指针:指针的指向可以发生变化,指针所指向的目标空间的值不能发生变化
const int *p;
int const *p;

指针常量:指针的指向不能发生变化,指针所指向的目标空间的值可以变化
int *const p;

指针和指针所指向的目标的空间值均不可以发生变化

const int *const p;

这里的发生变化指的是通过const修饰的变量名来修改变量的值

 

#define PI 3.14   宏在预处理阶段对语法类型不检查

const float pi= 3.14;  //pi不可修改,比宏的优点:检查类型

int main(){
    const float pi=3.14;

    //pi=3.14159;// error :向只读变量‘pi’赋值
    float *p=π
    *p=3.14159;   //警告:初始化丢弃了指针目标类型的限定,pi的值确实改了

    printf("%f\n", pi);
}

 

常量指针

 

int main(){
    int i=1;
    const int *p=&i;
    i=10; //正确
    //*p=100;//错误:向只读位置‘*p’赋值
    printf("%d\n",*p );
}
int main(){
    int i=1;
    int j=100;
    const int *p=&i;
    p=&j;
    printf("%d\n",*p ); //100
}

 

指针常量

 

int main(){
    int i=1;
    int j=100;
    int * const p=&i;

    *p=10;     //ok
    p=&j;    //错误:向只读变量‘p’赋值
    printf("%d\n",*p);
}

const int *const p;

 

 

int main(){
    int i=1;
    int j=100;
    const int *const p=&i;

     // p=&j;//错误:向只读变量‘p’赋值
     *p=10;//错误:向只读位置‘*p’赋值
    printf("%d\n",*p);
}