This probably due to optimizations. Since you declare const int n=9
, you're basically making a promise that you won't modify n
. So the compiler is free to optimize cout << n << endl;
to a simple cout << 9 << endl;
. I don't think the old value is stored anywhere else.
Nevertheless, this is undefined behavior.
I can confirm that the cause of this behavior is optimization, even on a debug build:
cout< >::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 >::operator<< (11582A8h)]
0115144D cmp esi,esp
0115144F call @ILT+325(__RTC_CheckEsp) (115114Ah)
n
doesn't even come into discussion.
If n
wasn't const
, the optimization would be illegal:
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 >::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 >::operator<< (0D582A8h)]
00D5144F cmp esi,esp
00D51451 call @ILT+325(__RTC_CheckEsp) (0D5114Ah)
Here, the value of n
is pushed on the argument stack because it's not const
.