C++ 更改“;常数int“;通过「;int*”;指针。惊喜

C++ 更改“;常数int“;通过「;int*”;指针。惊喜,c++,C++,可能重复: 让我们先看下面的代码。非常短的代码: int main() { const int n=9; int *p=(int*)&n; *p=5; cout<<*p<<endl; //result is 5 cout<<n<<endl; // 9 int a=n+1; cout<<a<<endl; // 10 } intmain() { 常数int

可能重复:

让我们先看下面的代码。非常短的代码:

int main()
{
    const int n=9;
    int *p=(int*)&n;
    *p=5;
    cout<<*p<<endl; //result is 5
    cout<<n<<endl;  // 9
    int a=n+1;
    cout<<a<<endl;  // 10
}
intmain()
{
常数int n=9;
int*p=(int*)&n;
*p=5;

cout这可能是由于优化。既然你声明了
const int n=9
,你基本上是在承诺你不会修改
n
。所以编译器可以自由优化
难道你违反了规则吗。编译器给你的回报没有任何保证。是的。我知道。实际上我们不应该像这样使用它这很有趣,对吧?我只是对隐藏的行为感到好奇。我认为这对改进有好处。:)你的解释似乎真的很有道理。@duleshi添加了代码来支持它。事实上,我是著名的stackoverflow的新来者,这是我的帖子!非常感谢你如此快速而精彩的回答!
    cout<<n<<endl;  
01151426  mov         esi,esp  
01151428  mov         eax,dword ptr [__imp_std::endl (11582B4h)]  
0115142D  push        eax  
0115142E  mov         edi,esp  

//HERE:
//
01151430  push        9  
//
//

01151432  mov         ecx,dword ptr [__imp_std::cout (11582B0h)]  
01151438  call        dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (11582ACh)]  
0115143E  cmp         edi,esp  
01151440  call        @ILT+325(__RTC_CheckEsp) (115114Ah)  
01151445  mov         ecx,eax  
01151447  call        dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (11582A8h)]  
0115144D  cmp         esi,esp  
0115144F  call        @ILT+325(__RTC_CheckEsp) (115114Ah)  
00D51426  mov         esi,esp  
00D51428  mov         eax,dword ptr [__imp_std::endl (0D582B4h)]  
00D5142D  push        eax  
00D5142E  mov         edi,esp  

//HERE
//
00D51430  mov         ecx,dword ptr [n]  
00D51433  push        ecx  
//
//

00D51434  mov         ecx,dword ptr [__imp_std::cout (0D582B0h)]  
00D5143A  call        dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (0D582ACh)]  
00D51440  cmp         edi,esp  
00D51442  call        @ILT+325(__RTC_CheckEsp) (0D5114Ah)  
00D51447  mov         ecx,eax  
00D51449  call        dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (0D582A8h)]  
00D5144F  cmp         esi,esp  
00D51451  call        @ILT+325(__RTC_CheckEsp) (0D5114Ah)