Two different values at the same memory address

前端 未结 7 748
春和景丽
春和景丽 2020-11-22 08:14

Code

#include 
using namespace std;

int main() {
    const int N = 22;
    int * pN = const_cast(&N);
    *pN = 33;
    co         


        
7条回答
  •  梦如初夏
    2020-11-22 09:01

    I had the same question (Why am I not able to modify the contents of const int even with const_cast?) . I think answered here wonderfully by everyone. Just adding the assembly output from compiler

    This is my original code

    const int y = 7;
    int* a = new int;
    a = const_cast(&y); 
    *a = 8;
    std::cout << (int)*(&y) << std::endl;
    

    This is the assembly output

    std::cout << (int)*(&y) << std::endl;
    00381CB6  push        offset std::endl > (03813C5h)  
    **00381CBB  push        7**  
    00381CBD  mov         ecx,dword ptr [_imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A (03900ACh)]  
    00381CC3  call        dword ptr [__imp_std::basic_ostream >::operator<< (03900B8h)]  
    00381CC9  mov         ecx,eax  
    00381CCB  call        dword ptr [__imp_std::basic_ostream >::operator<< (03900BCh)]  
    

    So the compiler will just replace the const variables with its actual value during compile time.

提交回复
热议问题