对于常量使用可变指针修改混乱 [英] Confusion regarding modification of const variable using pointers
问题描述
下面的示例我的理解添加混乱。我无法理解怎么可能修改常量局部变量。请帮我理解是相同的。
Following example added confusion in my understanding. I'm unable to understand how is it possible to modify the const variable local. Please help me to understand the same.
/* Compile code without optimization option */
// volatile.c
#include <stdio.h>
int main(void)
{
const int local = 10;
int *ptr = (int*) &local;
printf("Initial value of local : %d \n", local);
*ptr = 100;
printf("Modified value of local: %d \n", local);
return 0;
}
$ GCC volatile.c -o挥发性-save-临时工
$ gcc volatile.c -o volatile –save-temps
$ ./volatile
$ ./volatile
本地初始值:10
局部修改值:100
推荐答案
这是只需未定义行为如果我们看一下C99标准草案 6.7.3
的类型限定的段落的 4 的它说:
This is simply undefined behavior if we look at the C99 draft standard section 6.7.3
Type qualifiers paragraph 4 it says:
如果试图修改与通过使用常量限定类型定义的对象
与非const限定类型的左值的,其行为是不确定的。如果尝试是
通过制作使用左值来指与volatile限定类型定义的对象
具有非易失性限定的类型,其行为是不确定的。 115)
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. If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.115)
所以,你不能对结果的预期,你不应该这样做。
So you can not have any expectations on the results and you should not be doing this.
如果我们看一下段落的 2 的它说:
If we look at paragraph 2 it says:
与合格的类型相关的属性只对前pressions有意义的
是左值。 114)
The properties associated with qualified types are meaningful only for expressions that are lvalues.114)
和脚注 114
说:
实现可以放置一个const对象不是挥发性在只读区域
存储。此外,执行不需要这样一个对象,如果从未使用过它的地址分配存储空间。
The implementation may place a const object that is not volatile in a read-only region of storage. Moreover, the implementation need not allocate storage for such an object if its address is never used.
在总体上实现不必须做的常量的变量的只读的,但它可能会,但为R ..指出把一个自动变量在只读存储器会很难。
In general the implementation does not have to make const variables read-only but it may but as R.. points out placing an automatic variable in read-only memory would be hard.
这篇关于对于常量使用可变指针修改混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!