同一地址的变量如何产生 2 个不同的值?

How is a variable at the same address producing 2 different values?(同一地址的变量如何产生 2 个不同的值?)
本文介绍了同一地址的变量如何产生 2 个不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下:

#include <iostream>
using namespace std;

int main(void)
{
    const int a1 = 40;
    const int* b1 = &a1;
    char* c1 = (char *)(b1);
    *c1 = 'A';
    int *t = (int*)c1;


    cout << a1 << " " << *t << endl;
    cout << &a1 << " " << t << endl; 

    return 0;
}

这个的输出是:

40 65 
0xbfacbe8c 0xbfacbe8c

除非编译器进行优化,否则这对我来说几乎是不可能的.如何 ?

This almost seems impossible to me unless compiler is making optimizations. How ?

推荐答案

这是 未定义行为,您正在修改一个 const 变量,因此您对结果不抱任何期望.我们可以通过查看草案 C++ 标准部分 7.1.6.1 The cv-qualifiers 段落 4 看到这一点:

This is undefined behavior, you are modifying a const variable so you can have no expectation as to the results. We can see this by going to the draft C++ standard section 7.1.6.1 The cv-qualifiers paragraph 4 which says:

[...]任何在 const 对象的生命周期 (3.8) 期间对其进行修改的尝试都会导致未定义的行为.

[...]any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

甚至提供了一个例子:

const int* ciq = new const int (3); // initialized as required
int* iq = const_cast<int*>(ciq); // cast required
*iq = 4; // undefined: modifies a const object

1.3.24部分未定义行为的标准定义中,给出了以下可能的行为:

In the standard definition of undefined behaviour in section 1.3.24, gives the following possible behaviors:

[...] 允许的未定义行为范围从完全忽略具有不可预测结果的情况,到在翻译或程序执行期间以环境特征的记录方式表现(无论是否发布诊断消息),终止翻译或执行(发出诊断消息).[...]

[...] Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). [...]

这篇关于同一地址的变量如何产生 2 个不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)