通过非const指针修改const int
Modification of const int through a non-const pointer
#include <stdio.h>
int main(){
const int a = 10;
*(int*)(&a) = 9; // modify a
printf("%d", a);
return 0;
}
- 当我 运行 这段代码在 Xcode 上时,输出是 10(未更改)
- 当我在 Visual Studio 社区上 运行 这段代码时,输出为 9(已更改)
为什么?
此程序可以编译但表现出未定义的行为,可能会输出 9
或 10
或其他内容,或者可能会崩溃谁知道呢。
当您说 a
是 const
时,您保证不会尝试直接或间接更改 a
的值,并且编译器可能会做出某些假设。如果你违背承诺,可能会发生意想不到的事情。
Q: why?
解释一下,如果您尝试通过某些 non-const
指针访问来修改 const
变量值,它会调用 undefined behaviour.
根据 C11
标准,第 6.7.3 章,第 6 段。
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.
注:main()
推荐签名为int main(void)
.
const关键字用于不改变变量的值。如果强行完成,结果可能会出乎意料
#include <stdio.h>
int main(){
const int a = 10;
*(int*)(&a) = 9; // modify a
printf("%d", a);
return 0;
}
- 当我 运行 这段代码在 Xcode 上时,输出是 10(未更改)
- 当我在 Visual Studio 社区上 运行 这段代码时,输出为 9(已更改)
为什么?
此程序可以编译但表现出未定义的行为,可能会输出 9
或 10
或其他内容,或者可能会崩溃谁知道呢。
当您说 a
是 const
时,您保证不会尝试直接或间接更改 a
的值,并且编译器可能会做出某些假设。如果你违背承诺,可能会发生意想不到的事情。
Q: why?
解释一下,如果您尝试通过某些 non-const
指针访问来修改 const
变量值,它会调用 undefined behaviour.
根据 C11
标准,第 6.7.3 章,第 6 段。
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.
注:main()
推荐签名为int main(void)
.
const关键字用于不改变变量的值。如果强行完成,结果可能会出乎意料