gpt4 book ai didi

c++ - 里面的const变量是什么?

转载 作者:行者123 更新时间:2023-11-30 18:55:14 25 4
gpt4 key购买 nike

#include <stdio.h>

int main()
{
const int a=1;
printf("a's address is %p\r\n",&a);
printf("input a's address\r\n");
int *p=NULL;
//here let p point to a;
scanf("%p",&p);
printf("p point to %p\r\n",p);
*p=100;
// I suppose a will be 100, but acturlly a is still 1...
printf("a's value is %d\r\n",a);
printf("*p's value is %d\r\n",*p);

return 0;
}

为什么是a仍然1而不是100

但是如果我声明 a如:

int a =1;

它有效!

那么,进展如何?

最佳答案

代码中有几个地方可以调用未定义的行为,这意味着任何事情都可能发生。 a 可以是 1100"puppy"

首先,你不能这样做

scanf("%p",&p);
printf("p point to %p\r\n",p);
*p=100;

因为你可能不拥有该内存。即使你这样做了,写入它也可能是非法的。就像这里的情况一样。

如果您这样做(更改a地址处的值)或使用const_cast,然后尝试修改a,则会出现'未定义行为的另一个实例。您做出了 promise aconst - 不要更改它。

结果是 UB,这种行为可能会发生,因为编译器将 printf("a's value is %d\r\n",a); 优化为简单的 printf("a 的值是 %d\r\n",1);,因为它相信你不会修改 a(为他感到羞耻)。

关于c++ - 里面的const变量是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28301147/

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