Strange behavior of const_cast [duplicate]

Consider the following code:

I declare a new reference end assign it to value a via const_cast. Then I just increase the reference value print the addresses and values.

#include <iostream>
using namespace std;
int main()
{
    const int a = 7;
    int &b = const_cast<int&>(a);
    ++b;
    cout<<"Addresses  "<<&a<<" "<<&b<<endl;
    cout<<"Values  "<<a<<" "<<b<<endl;
}

//output
Addresses  0x7fff11f8e30c 0x7fff11f8e30c
Values  7 8

How can i have 2 different values in the same address??


Solution 1:

Because modifying a variable declared to be const is undefined behavior, literally anything can happen.

Solution 2:

Modifying a constant object gives undefined behaviour, so your program could (in principle) do anything.

One reason for leaving this behaviour undefined is to allow the optimisation of replacing a constant variable with its value (since you've stated that the value can never change). That's what is happening here: a is replaced with the value 7 at compile time, and so will keep that value whatever you try to do to it at run time.

Solution 3:

Even though const_cast may remove constness from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const invokes undefined behavior.

check out the example here for more illustration:

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

Solution 4:

Any attempt to modify an object that is itself declared const by means of const_cast results in undefined behavior according to the ISO C++ Standard.

When the we refer "const object", it intends to say that the memory where the object is located may be write-protected. That is, a variable or expression of const type may denote an object stored in write-protected memory and any attempt to modify the object results in undefined behavior

EDIT: Refer this site for more info

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1994/N0571.asc