1
#include <iostream>

using namespace std;

int main()
{
    const int kiNum = 100;
    int* ptr = const_cast<int*>(&kiNum);
    *ptr = 200; 
    cout<<"kiNum: "<<kiNum; // The value still prints 100 on the console??
    return 0;
}

output:
kiNum = 100 

In the above code snippet , i am trying to change the value of a const integer, after const_cast and then change the value at the address, but the console still prints the old value (i am using visual studio 2012)

horns
  • 1,843
  • 1
  • 19
  • 26
  • This is undefined behavior see [How is a variable at the same address producing 2 different values?](http://stackoverflow.com/q/22656734/1708801) – Shafik Yaghmour Mar 26 '15 at 17:09

1 Answers1

5

Writing to something which is defined as const is undefined (assuming you cast away the const of course).

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

It's a pretty accurate website. If you have issues with a language feature its always worth looking up there IMHO.

qeadz
  • 1,476
  • 1
  • 9
  • 17