0

Run the code below:

#include <iostream>

int main()
{
   const int NUM = 1;
   int *p = (int *)&NUM;
   *p = 2;

   std::cout << *p << "\n";
   std::cout << NUM << "\n";
   return 0;
}

The output of the program above is: 2 1

The expected output was: 2 2

Can anyone please explain why the value of NUM is 1? The same can be tested with https://www.onlinegdb.com/

  • 1
    it's undefined behavior. [Can we change the value of an object defined with const through pointers?](https://stackoverflow.com/q/3801557/995714), [Undefined behaviour of const](https://stackoverflow.com/q/21790926/995714), [C++ const changed through pointer, or is it?](https://stackoverflow.com/q/41096733/995714), [Change "const int" via an "int *" pointer. Surprising and interesting](https://stackoverflow.com/q/11641613/995714), [How is a variable at the same address producing 2 different values?](https://stackoverflow.com/q/22656734/995714) – phuclv Jun 04 '22 at 03:27
  • 1
    Practically, the compiler knows `NUM` is constant. It can't be changed, [so in the name of speed](https://en.cppreference.com/w/cpp/language/as_if) it's perfectly fine to replace `std::cout << NUM << "\n";` with `std::cout << "1\n";` or something even lighter-weight. – user4581301 Jun 04 '22 at 04:26

1 Answers1

0

A const is a read-only value. You are trying to do something that is not allowed so you should have Undefined behaviours like this one.

WrathionTBP
  • 832
  • 2
  • 6