我们可以通过指针更改用const定义的对象的值吗? [英] Can we change the value of an object defined with const through pointers?

查看:160
本文介绍了我们可以通过指针更改用const定义的对象的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
int main()
{
    const int a = 12;
    int *p;
    p = &a;
    *p = 70;
}

它将起作用吗?

推荐答案

这是未定义的行为,这意味着基于标准,您无法预测尝试此操作时将发生的情况。根据特定的计算机,编译器和程序状态,它可能会执行不同的操作。

It's "undefined behavior," meaning that based on the standard you can't predict what will happen when you try this. It may do different things depending on the particular machine, compiler, and state of the program.

在这种情况下,最常见的答案是是。变量(无论是否为const)都只是内存中的一个位置,您可以打破constness规则并直接覆盖它。 (当然,如果程序的其他部分取决于其const数据是否恒定,这将导致严重的错误!)

In this case, what will most often happen is that the answer will be "yes." A variable, const or not, is just a location in memory, and you can break the rules of constness and simply overwrite it. (Of course this will cause a severe bug if some other part of the program is depending on its const data being constant!)

但是在某些情况下-最典型的情况是 const static 数据-编译器可能会将此类变量放在内存的只读区域中。例如,MSVC通常将const静态整数放在可执行文件的.text段中,这意味着如果您尝试向其写入操作,操作系统将抛出保护错误,并且程序将崩溃。

However in some cases -- most typically for const static data -- the compiler may put such variables in a read-only region of memory. MSVC, for example, usually puts const static ints in .text segment of the executable, which means that the operating system will throw a protection fault if you try to write to it, and the program will crash.

在编译器和计算机的某些其他组合中,可能会发生完全不同的事情。您可以肯定地预测的一件事是,无论谁必须阅读您的代码,此模式都会使人烦恼。

In some other combination of compiler and machine, something entirely different may happen. The one thing you can predict for sure is that this pattern will annoy whoever has to read your code.

这篇关于我们可以通过指针更改用const定义的对象的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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