未定义的const行为 [英] Undefined behaviour of const

查看:329
本文介绍了未定义的const行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有想过我会问这个问题,但我不知道为什么会发生这种情况。

I never thought I will be going to ask this question but I have no idea why this happens.

const int a = 3; 
int *ptr;
ptr = (int*)( &a );
printf( "A=%d\n", &a );
*ptr = 5; 
printf( "A=%d\n", ptr );
printf( "A=%d\n", a );
printf( "A=%d\n", *ptr );

输出

A=6945404
A=6945404
A=3
A=5

这怎么会发生?一个内存位置如何保存两个不同的值?我搜索过,我发现的是未定义的行为未定义。那没有任何意义。必须有解释。

How can this happen? How can one memory location hold two different values? I searched around and all I find is undefined behavior is undefined. Well that does not make any sense. There must be an explanation.

编辑

c $ c> Marks 回答有一定的意义,但仍然我不知道const添加到语言,以便用户不会无意中更改的值。我得到旧的编译器允许你这样做,但我试过这个VS 2012和我有相同的行为。然后再次按 haccks 说,一个内存位置不能保存两个值,它看起来像它,然后第二个值存储在哪里?

I get it, Marks answer makes alot of sense but still I wonder that const was added into the language so that user does not change the value unintentionally. I get that old compilers allows you to do that but I tried this on VS 2012 and I got the same behavior. Then again as haccks said, one memory location can't hold two values it looks like it does, then where is the second value stored?

推荐答案

优化程序可以确定 a 是一个常量值, 3 。这解释了你看到的,虽然不能保证是真正发生的事情。您需要研究生成的汇编输出。

The optimizer can determine that a is a constant value, and replace any reference to it with the literal 3. That explains what you see, although there's no guarantee that's what's actually happening. You'd need to study the generated assembly output for that.

这篇关于未定义的const行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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