开发者

Unexpected output

#include <iostream>

int main() 
{

    const int i=10;
    int *p =(int *) &i;
    *p = 5;
    cout<<&i<<" "<&开发者_StackOverflowlt;p<<"\n";
    cout<<i<<" "<<*p;
    return 0;
}

Output:

0x22ff44 0x22ff44

10 5

Please Explain.


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.


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜