title: C++ const changed through pointer, or is it?
body: <p>In c it's possible to change const using pointers like so:</p>
  
  <pre><code>//mainc.c
  #include &lt;stdio.h&gt;
  
  int main(int argc, char** argv) {
      const int i = 5;
      const int *cpi = &amp;i;
  
      printf("  5:\n");
      printf("%d\n", &amp;i);
      printf("%d\n", i);
      printf("%d\n", cpi);    
      printf("%d\n", *cpi);   
  
      *((int*)cpi) = 8;
      printf("  8?:\n");
      printf("%d\n", &amp;i);
      printf("%d\n", i);
      printf("%d\n", cpi);
      printf("%d\n", *cpi);
  }
  </code></pre>
  
  <p>The constant is changed as can be seen in the output:
  <a href="https://i.stack.imgur.com/9xoT9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9xoT9.png" alt="mainc output"></a></p>
  
  <p>If we try the same in c++:</p>
  
  <pre><code>//main.cpp
  #include &lt;iostream&gt;
  
  using std::cout;
  using std::endl;
  
  int main(int argc, char** argv) {
      const int i = 5;
      const int *cpi = &amp;i;
  
      cout &lt;&lt; "  5:" &lt;&lt; '\n';
      cout &lt;&lt; &amp;i &lt;&lt; '\n';
      cout &lt;&lt; i &lt;&lt; '\n';
      cout &lt;&lt; cpi &lt;&lt; '\n';    
      cout &lt;&lt; *cpi &lt;&lt; '\n';   
  
      *((int*)cpi) = 8;
      cout &lt;&lt; "  8?:" &lt;&lt; '\n';
      cout &lt;&lt; &amp;i &lt;&lt; '\n';
      cout &lt;&lt; i &lt;&lt; '\n';
      cout &lt;&lt; cpi &lt;&lt; '\n';
      cout &lt;&lt; *cpi &lt;&lt; '\n';
  
      int* addr = (int*)0x28ff24;
      cout &lt;&lt; *addr &lt;&lt; '\n';
  }
  </code></pre>
  
  <p>The result is not so clear:
  <a href="https://i.stack.imgur.com/rs978.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rs978.png" alt="main output"></a></p>
  
  <p>From the output is looks like <code>i</code> is still <code>5</code> and is still located at <code>0x28ff24</code> so the const is unchanged. But in the same time <code>cpi</code> is also <code>0x28ff24</code> (the same as <code>&amp;i</code>) but the value it points to is <code>8</code> (not <code>5</code>).</p>
  
  <p>Can someone please explain what kind of magic is happening here?</p>
  
  <p>Explained here: <a href="https://stackoverflow.com/a/41098196/2277240">https://stackoverflow.com/a/41098196/2277240</a></p>