(b); *c=40" /> (b); *c=40" /> (b); *c=40"/>

Why isn't assigning c*=40 change the value of a?

52 Views Asked by At
#include <iostream>
using namespace std;
int main() {
   const int a = 20;
   const int* b = &a;
   cout<<"b* = "<<*b<<"\n";
   int* c=const_cast<int *>(b);
   *c=40;
   cout<<"b* = "<<*b<<" a = "<<a;
   return 0;
}
2

There are 2 best solutions below

0
mightyWOZ On

You are trying to modify a const object, this behaviour is undefined.

From C++ spec section 10.1.7.1 point 4

any attempt to modify a const object during its lifetime results in undefined behavior.

const int* ciq = new const int (3);  // initialized as required
int* iq = const_cast<int*>(ciq);     // cast required
*iq = 4;                             // undefined: modifies a const object
0
C0de On

The value of a is not changing because you are using const int a = 20; to change the value of a you can simply declare int a =20;