0

I am trying to change the value of a const int variable (should not be done ideally). This is how I did it.

const int x{5};               //line 1
int* y{const_cast<int*>(&x)}; //line 2

std::cout<<y<<" "<<&x<<endl;  //line 3

*y = 10;                      //line 4
std::cout<<*y<<" "<<x<<endl;  //line 5
std::cout<<y<<" "<<&x<<endl;  //line 6

At line 2, I took away the constness of the constant variable x and made y point to it.

At line 3, the memory address of y and x are same.

But, after I changed the value of y at line 4, line 5 prints *y=10 and x=5, and the weird thing is line 6 still shows the same memory address of y and x.

Can anyone help me understand how things are working internally?

I only want to understand the cause of how the program shows 2 different values at the same memory location.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Why are you trying to change a constant if they are created to not be changed just to be readed? – WrathionTBP May 30 '22 at 06:17
  • 1
    What did you expect to happen when you do something that is not allowed? You are experiencing undefined behaviour here, anything is allowed to happen. Probably `x` got inlined in line 5. – Lukas-T May 30 '22 at 06:18
  • 1
    Modifying const object produces _undefined behavior_. If you want to know what your implementation does internally, study the generated assembly. Exemplary demo: https://godbolt.org/z/6hceYfj16. – Daniel Langr May 30 '22 at 06:18
  • @churill, I expected the same value of *y and x as the memory locations are same. Isn't this what should have happened? – Raj Kumar Singh May 30 '22 at 06:23
  • 2
    @RajKumarSingh Undefined behavior = anything can happen = nothing particular should happen – Daniel Langr May 30 '22 at 06:30
  • @RajKumarSingh "*I expected the same value of `*y` and `x`*" - why did you expect *writing* to a *read-only* object would yield *any* meaningful results at all? You broke the rules, so this is a consequence. – Remy Lebeau May 30 '22 at 07:34
  • How things are working internally? The compiler probably assumes that as x is constant, it doesn't need to access the memory location allocated for x in line 5, and just print 5. – Uri Raz May 30 '22 at 07:50

0 Answers0