意外的输出
#include <iostream>
int main()
{
const int i=10;
int *p =(int *) &i;
*p = 5;
cout<<&i<<" "<<p<<"\n";
cout<<i<<" "<<*p;
return 0;
}
输出:
0x22ff44 0x22ff44
10 5
请解释一下。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,你的代码显然包含未定义的行为,所以任何事情都有可能发生。
在这种情况下,我相信会发生这样的情况:
在 C++ 中,const int 被认为是编译时常量。在您的示例中,编译器基本上将您的“i”替换为数字 10。
Well, your code obviously contains undefined behaviour, so anything can happen.
In this case, I believe what happens is this:
In C++, const ints are considered to be compile-time constants. In your example, the compiler basically replaces your "i" with number 10.
您尝试修改 const 对象,因此行为是
不明确的。编译器有权假设 const
对象的值不会改变,这可能解释了
你看到的症状。编译器也有权将
只读内存中的 const 对象。它通常不会这样做
具有自动生命周期的变量,但如果 const 具有自动生命周期,则很多变量都会
静态寿命;在这种情况下,程序将崩溃(在大多数情况下)
系统)。
You've attempted to modify a const object, so the behavior is
undefined. The compiler has the right to suppose that the const
object's value doesn't change, which probably explains the
symptoms you see. The compiler also has the right to put the
const object in read only memory. It generally won't do so for
a variable with auto lifetime, but a lot will if the const has
static lifetime; in that case, the program will crash (on most
systems).
我会尝试一下:由于该输出没有逻辑原因,编译器必须将那个可怜的
cout< 优化为简单的
"cout< ;<“10”
。但这只是一种预感。I'll take a shot at it: since there's no logical reason for that output, the compiler must have optimised that wretched
cout<<i<<" "
to a simple"cout<<"10 "
. But it's just a hunch.