mercredi 26 juillet 2017

C++ forced conservation from const int* to int*

The code as below:

#include <iostream>
using namespace std;
int main() {
  const int a = 4;
  const int *p = &a;
  int *test = const_cast<int *>(p);
  *test = 5;
  cout<<p<<endl;
  cout<<&a<<endl;
  cout << *(&a) << endl;  // print 5
  cout << a << endl;   //print 4
}

why the former output 5 and the latter output 5. I am confused about that, anyone can explain that to me? Thank you very much!

Aucun commentaire:

Enregistrer un commentaire