-1
#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;
}
mightyWOZ
  • 7,946
  • 3
  • 29
  • 46
  • Why should a value of a `const` object change? – Evg Jul 18 '21 at 06:34
  • The expression is not as you describe - `*c = 40` (in your code) and `c *= 40` (in the title to the question) mean different things. In any event, you are using `const_cast` to force the compiler to later permit an apparent change of something that is actually `const` - so your code has *undefined* behaviour. By definition, the C++ standard does not define what happens when behaviour is undefined, so any outcome is possible (e.g. not changing something that you expect to change) and the compiler is not required to emit diagnostics (e.g. errors or warnings) about undefined behaviour. – Peter Jul 18 '21 at 06:46

2 Answers2

1

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
mightyWOZ
  • 7,946
  • 3
  • 29
  • 46
0

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;

C0de
  • 1
  • 2