通过非const的指针const int的修改 [英] Modification of const int through a non-const pointer
本文介绍了通过非const的指针const int的修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
的#include<&stdio.h中GT;诠释主(){
const int的一个= 10;
*为(int *)(安培; A)= 9; //修改
的printf(%d个,一);
返回0;
}
- 当我运行在X code此code,输出为10(无变化)
- 当我运行的Visual Studio社区这个code,输出为9(改变)
为什么?
解决方案
的问:为什么?的
块引用>答:未定义行为
要解释一下,如果试图通过访问修改
常量
变量的值是通过一些非const
指针,它调用未定义行为。按
C11
标准,章6.7.3条第6款。
如果试图修改通过使用非const限定型左值与一个const限定的类型定义的对象,行为是不确定的。
块引用>注:的推荐签名
的main()
是INT主要(无效)
#include <stdio.h> int main(){ const int a = 10; *(int*)(&a) = 9; // modify a printf("%d", a); return 0; }
- When I run this code on Xcode, the output is 10 (not changed)
- When I run this code on Visual Studio Community, the output is 9 (changed)
Why?
解决方案Q: why?
Ans: undefined behaviour.
To explain, if you try to modify a
const
variable value by accessing is through somenon-const
pointer, it invokes undefined behaviour.As per
C11
standard, chapter 6.7.3, paragraph 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.
Note: The recommended signature of
main()
isint main(void)
.这篇关于通过非const的指针const int的修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文