const全局变量和const局部变量是否可以修改

注意:以下程序编辑和运行于centos7 gcc环境,不同的编译器可能略有不同

#include <stdio.h>
#include <stdlib.h>

const int a = 10;

int main()
{
//      int *pa = &a; //warning: initialization discards ‘const’ qualifier from pointer target type [enabled by default]
//      *pa = 1000;
//      printf("a = %d \n,",a);
        
//      a = 100; //error: assignment of read-only variable ‘a’
//      printf("a = %d \n,",a);

		int *pza = (int *)&a;
//      *pza = 10000;      //./test       运行时报错 Segmentation fault (core dumped)
        printf("a = %d \n,",a);


        const int b = 20;
//      b = 200; //error: assignment of read-only variable ‘b’

//      printf("b = %d \n",b);  
//      int *pb = &b; //warning: initialization discards ‘const’ qualifier from pointer target type [enabled by default]

//      *pb = 2000;
//      printf("b = %d \n",b);
        int *pzb = (int *)&b;
        *pzb = 20000;
        printf("b = %d \n",b);

        return 0;
}
                                                              
./test
a = 10 
,b = 20000 

  1. const局部变量存储在栈中,可通过指针修改其值;(注意:不能直接修改)
  2. const全局变量存储在全局存储空间,其值只有可读属性,所以修改会导致崩溃 (直接和间接都不能修改)
  3. int *pza = (int *)&a; a的地址类型是const int,所以必须强制类型转换才可以赋值给int *类型的变量。
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页