Getting the same value of the const variable even after changing it through const_cast
<p>Consider the below code snippet:</p>

<pre><code>int main()
{
    const int i=3;
    int *ptr;

    ptr=const_cast&lt;int*&gt;(&amp;i);
    *ptr=5;

    cout&lt;&lt;"i= "&lt;&lt;i&lt;&lt;endl;  &lt;------------------- statement 1
    cout&lt;&lt;"*ptr= "&lt;&lt;*ptr&lt;&lt;endl;  &lt;------------- statement 2

    return 0;
}
</code></pre>

<p>I am getting the output as:    </p>

<pre><code>i= 3
*ptr= 5
</code></pre>

<p><a href="http://ideone.com/Bvme6" rel="nofollow">http://ideone.com/Bvme6</a>     </p>

<p>Why is the value of <code>i</code> is not changed through pointer?</p>

<p>I know casting away the const-ness of a variable which is explicitly declared as const and modifying its value is 'Undefined Behavior'. I am curious to know: Is it any compiler optimization mechanism that 'compiler replaces the variable in the program with the value'?.
It means the statement 1 is interpreted by the compiler as:</p>

<pre><code>cout&lt;&lt;"i= "&lt;&lt;3&lt;&lt;endl;
</code></pre>

<p>Even if the statement </p>

<pre><code>ptr=const_cast&lt;int*&gt;(&amp;i);    
</code></pre>

<p>is replaced by</p>

<pre><code> ptr=(int*)(&amp;i);
</code></pre>

<p>I am getting the same output: <a href="http://ideone.com/5lzJA" rel="nofollow">http://ideone.com/5lzJA</a>    </p>
