关于使用指针修改 const 变量的困惑 [英] Confusion regarding modification of const variable using pointers

查看:36
本文介绍了关于使用指针修改 const 变量的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下示例在我的理解中增加了混乱.我无法理解如何修改本地的 const 变量.请帮助我理解相同的内容.

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 
", local);

     *ptr = 100;

     printf("Modified value of local: %d 
", local);

     return 0;
}

$ gcc volatile.c -o volatile –save-temps

$ gcc volatile.c -o volatile –save-temps

$ ./volatile

$ ./volatile

local 的初始值:10

Initial value of local : 10

local 的修改值:100

Modified value of local: 100

推荐答案

这只是未定义行为 如果我们查看 C99 草案标准部分 6.7.3 Type qualifiers 段落 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 限定类型定义的对象对于具有非 const 限定类型的左值,行为未定义.如果尝试是通过使用左值引用具有 volatile 限定类型的对象对于非 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段,它说:

与限定类型关联的属性仅对符合以下条件的表达式有意义是左值.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.

一般来说,实现不必使 const 变量 只读 但它可能只是作为 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.

这篇关于关于使用指针修改 const 变量的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆