在同一地址的变量如何产生2个不同的值? [英] How is a variable at the same address producing 2 different values?

查看:97
本文介绍了在同一地址的变量如何产生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

这对我来说似乎是不可能的,除非编译器正在进行优化。怎么样 ?

解决方案

这是未定义的行为,您正在修改一个常量变量,因此您不能期望结果。我们可以通过转到草稿C ++标准部分 7.1.6.1 cv-qualifiers 段落 4



>

甚至提供了一个示例:

  const int * ciq = new const int(3); //根据需要初始化
int * iq = const_cast< int *>(ciq); // cast required
* iq = 4; // undefined:修改const对象

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


..]允许的未定义行为的范围从完全以不可预测的结果忽略情况,在以文件化的环境特征(有或没有发出
a诊断消息)的翻译或程序执行期间行为,或执行(随着诊断消息的发出)。 [...]



Consider this :

#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;
}

The output for this is :

40 65 
0xbfacbe8c 0xbfacbe8c

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

解决方案

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:

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

and even provides an example:

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

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个不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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