gpt4 book ai didi

c - 修改常量变量(const)

转载 作者:行者123 更新时间:2023-11-30 17:12:39 25 4
gpt4 key购买 nike

我遇到了这段代码,我可以在其中修改 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;
}

输出:

value at ptr is : [10]

Address pointed by ptr : [0xbf9e614c]

value at ptr is : [11]

11

最佳答案

不,这是undefined behaviour .

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

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

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.

关于c - 修改常量变量(const),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31379119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com