1

Memory address shows two different values.

We have const variable (a) and we put the address of the variable into two pointers (b and c). After changing the value at the address in one of the pointers (c), we had a situation where the same memory address has two different values. Is there any explanation for this behavior?

#include <iostream> 
int main(void)
{
    const int a = 99;
    const int *b = &a;
    int *c = (int *)b;
    std::cout << &a << " - " << a << '\n';
    std::cout << b << " - " << *b << '\n';
    std::cout << c << " - " << *c << "\n\n";
    *c = 61;
    std::cout << &a << " - " << a << '\n';
    std::cout << b << " - " << *b << '\n';
    std::cout << c << " - " << *c << '\n';
    return 0;
}

//here are the result(output)

003CFAA4 - 99 003CFAA4 - 99 003CFAA4 - 99

003CFAA4 - 99 003CFAA4 - 61 003CFAA4 - 61

Armen
  • 11
  • 2
  • [Modifying a const int in C++](//stackoverflow.com/a/21842344) Which basically says this is UB as you are writing to a location of a `const` variable. – 001 Jan 16 '19 at 20:09
  • Possible duplicate of [Can we change the value of an object defined with const through pointers?](https://stackoverflow.com/questions/3801557/can-we-change-the-value-of-an-object-defined-with-const-through-pointers) – paxdiablo Jan 16 '19 at 20:13
  • The explanation? You broke the rules. When you do something that involves undefined behaviour, the results are, well, undefined :-) What exactly did you think `const` meant in this context? – paxdiablo Jan 16 '19 at 20:15

0 Answers0