【问题标题】:Modifying a constant variable (const) [duplicate]修改常量变量(const)[重复]
【发布时间】:2015-10-01 11:11:55
【问题描述】:

我遇到了这段代码,我可以在其中修改const int 变量的值!但这是一个错误还是一个黑客?请澄清一下:

#include<stdio.h>
int main(void)
{
    const int a = 10;
    int* ptr = &a;

    printf("\n value at ptr is  : [%d]\n",*ptr);
    printf("\n Address pointed by ptr  : [%p]\n",(unsigned int*)ptr);

    *ptr = 11;
    printf("\n value at ptr is  : [%d]\n",*ptr);
    printf("\n %d",a);

    return 0;
}

输出:

ptr 的值是:[10]

ptr 指向的地址:[0xbf9e614c]

ptr 的值是:[11]

11

【问题讨论】:

    标签: c pointers constants


    【解决方案1】:

    不,这是undefined behaviour。

    如果您尝试通过非 const 限定符指针修改 const 限定变量,它会调用 UB。

    引用 C11,第 §6.7.3 章,类型限定符

    如果尝试通过使用非const 限定类型的左值来修改使用const 限定类型定义的对象,则行为未定义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 2011-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多