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

查看:27
本文介绍了我们可以通过指针更改用 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,只是内存中的一个位置,您可以打破 const 的规则并简单地覆盖它.(当然,如果程序的某些其他部分依赖于其 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 static ints 放在可执行文件的 .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天全站免登陆