1

I'm trying to write a program that changes the value of a const variable. I know this shouldn't be done this in the first place and I'm doing this just to know how this happen.

I've already read other questions about this but I'm not trying to know how to do it but why it isn't happening in my program. This is the code I wrote:

int main()
{
    const int a = 5;

    int *pointer_a = const_cast<int*>(&a);

    *pointer_a = 6;

    // Address of a
    std::cout << &a << std::endl;
    // Prints 5 while memory says it is 6
    std::cout << a << std::endl;

    // Address that pointer points too
    std::cout << pointer_a << std::endl;
    // Prints 6
    std::cout << *pointer_a << std::endl;
}

What I noticed while debugging this program is that in fact the value at the memory address of a gets updated. It does change the value of a from 5 to 6.

The IDE (Visual Studio) also shows the value of a to be 6 but when printing it to the console, it prints 5. Why does this happen when the current value on the memory is 6?.

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
Vasco Ferreira
  • 2,151
  • 2
  • 15
  • 21
  • 4
    The only way to explain undefined behavior is to look at the assembly code the compiler produced and see what it's actually doing at that level. My guess would be that the compiler is hardcoding the constant `5` into the `<<` operator's arguments-list, because it "knows" that (in a well-formed program) `a` will always contain the value `5`, and therefore it doesn't have to bother with looking at `a`'s memory location at runtime. – Jeremy Friesner May 23 '20 at 22:23

2 Answers2

3

It is undefined behaviour to modify a value which is initially declared as const.

https://en.cppreference.com/w/cpp/language/const_cast:

const_cast makes it possible to form a reference or pointer to non-const type that is actually referring to a const object. Modifying a const object through a non-const access path results in undefined behavior.

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
1

try turning off compiler optimization flags (Project Properties, C/C++, Optimization)

dgrandm
  • 375
  • 3
  • 12