Casting a const int to a pointer? [duplicate]

与世无争的帅哥 提交于 2019-12-13 04:34:24

问题


Possible Duplicate:
Modifying a const through a non-const pointer

I have the following code:

const int x = 5;
int *p = (int*)&x;

*p = 2; // Line 1

cout << x << " - " << *p << endl;
cout << &x << " - " << p << endl;

And got the results:

5 - 2
0012FF28 - 0012FF28

I know the code is weird and should never do it. But I wondered why the same address but got different result? And where the Line 1 store the number 2?


回答1:


Because changing the value of an inherently const variable in anyway is Undefined Behavior[Ref #1].

Once you did:

*p = 2; // Line 1

All bets are off, and your code is no longer a valid C++ code, You cannot expect any particular behavior once that line was written. To speculate why an Undefined Behavior gives any particular behavior is pointless because it is allowed to show any behavior[Ref #2] that is the meaning of Undefined Behavior.


[Ref #1]
C++03 Standard 7.1.5.1 The cv-qualifiers:
Para 4:

Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

[Ref #2]
C++03 Standard 1.3.24:

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:


Declaring something const gives the compiler permission to assume that that value will not change. This means that they can use an "immediate" instruction to load the value 5, rather than referencing the location (if any) assigned to x.

Further, modifying a const violates the assurance you gave the compiler that that "variable" would not be modified, and could produce a variety of unanticipated behaviors.




回答3:


while some compilers do allocate an address for const values, it is a big no-no to access it. the reason you get 5-2 is because the compiler is replacing x directly with 5, even though you modified the address where x would have been given an address if it were not const and unless you access x's value through p* you are going to get 5 every time no matter what you do - also, p* may yield an undefined value since the getting the address of a const may actually fail with some compilers (and i think it should with all of them, personally)



来源:https://stackoverflow.com/questions/10792757/casting-a-const-int-to-a-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!