0
#include <iostream>

using namespace std;

int main(int argc, char const *argv[])
{
    const int a = 1;

    int* b;

    b = (int*)&a;

    *b = 6;

    cout << &a << endl;
    cout << b << endl;

    cout << a << endl;
    cout << *(&a) << endl;
    cout << *b << endl;

    return 0;
}

The output is as follows:

0x7ffc42aeb464
0x7ffc42aeb464
1
1
6

As the result, the memory address is same but the value is different. What is the reason?

Michael Tsai
  • 751
  • 2
  • 11
  • 21
  • 1
    This is UB. Const variables are not supposed to change their value – Teivaz Jul 03 '21 at 09:19
  • `b = (int*)&a;` is "wrong". You are telling the compiler that you don't care about constcorrectness, you say "help from the compiler to prevent errors? Pfftt, not for me", then you modify something that cannot be modifed. Thats not possible in a valid C++ program – 463035818_is_not_an_ai Jul 03 '21 at 09:27
  • @463035818_is_not_a_number but I have already changed the value in the memory, how can it output the original value? – Michael Tsai Jul 03 '21 at 09:44
  • code you write is not instructions that work on memory and cpu, code you write is an abstract description of what the resulting program should do. Modifying something that cannot be modified is just not possible. Its like I tell you "Walk without walking. Open the door without opening the door". Whatever you do is neither correct nor wrong, its my instructions that were wrong – 463035818_is_not_an_ai Jul 03 '21 at 09:48
  • 2
    you need to understand the concept of [undefined behavior](https://en.cppreference.com/w/cpp/language/ub). Just because code compiles without errors does not mean that it is valid code – 463035818_is_not_an_ai Jul 03 '21 at 09:52
  • You lie to the compiler, and then the program doesn't work as you expect. Due to this **undefined behavior**, the program may crash (*which is what I saw*), may produce unexpected results (*which is what you saw*), may email your browser history to your grandmother, make awaken Cthulhu from his slumber in the sunken city of R'lyeh, or worst of all... may appear to work. – Eljay Jul 03 '21 at 13:33

1 Answers1

0

Because you have cast it to non-const in (int*)&a. As I remember, this is undefined behavior.

Afshin
  • 8,839
  • 1
  • 18
  • 53