人类的孤独像是一种与生俱来的残疾。

关于warning: initialization discards ‘const’ qualifier from pointer target type [enabled by default]

C语言 smallfish 2633℃

话不多说,先上代码

 #include <stdio.h>
 
int main(int argc, char *argv[])
{
     const int a = 10;
     int *p = &a;
 
     printf("a = %d, *p = %d, p = %p\n", a, *p , p);
     *p = 20; //重点
     printf("a = %d, *p = %d, p = %p\n", a, *p , p);
 
     return 0;
}

如果不上编译器,很直观的会认为这段代码妥妥的有问题,因为p指向的是一个const变量a,变量a本应该存于.rodata段,即只读段,因此这段代码肯定编译通不过。然而,奇怪的是编译器放过去了(gcc-4.6),只放出来一个警告,且自动地将const int转为int。真心觉得巨坑啊。不过换个角度说,如果gcc不是给的警告,而是直接error。会不会又有人说gcc设计得不智能?既然我都有意用*p去修改一个const值,那说明使用者的确是想做这个操作的,那不如就“智能”地转换吧。当然如果使用者本意并不是要修改const值,仅是无意之举,那就自己哭去吧。当然gcc还是厚道的给了警告,再不注意那就真没办法了。

转载请注明:OpenMind » 关于warning: initialization discards ‘const’ qualifier from pointer target type [enabled by default]

喜欢 (1)