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

查看:23
本文介绍了我们可以通过指针改变用 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.

在这种情况下,最常发生的是答案是是".变量,无论是否为常量,都只是内存中的一个位置,您可以打破常量的规则并简单地覆盖它.(当然,如果程序的其他部分依赖于其常量数据的常量,这将导致严重的错误!)

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为例,它通常在可执行文件的.text段中放置const static ints,这意味着如果您尝试写入它,操作系统将抛出保护错误,程序将崩溃.

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天全站免登陆