mercredi 30 août 2017

Why an int pointer points to a const_casted const int pointer cannot really modify the value of const int? [duplicate]

This question already has an answer here:

Consider following codes

#include <iostream>
using namespace std;

int main() {
    const int i = 10, *cpi =& i;
    int *pi = const_cast<int*>(cpi);
    *pi = 100;
    cout<<*pi<<" "<<*cpi<<" "<<i<<endl;
    // 100 100 10
    return 0;
}

I used const_cast<int*>(cpi) to cast cpi from const int* to int*. And use const_casted int pointer to modify const int. The value of *cpi and *pi are as my expectation.

However, why i is still 10? Did compile create a second int value to store these 2 values?

Aucun commentaire:

Enregistrer un commentaire