Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>They are correct, it is undefined behaviour. You're not allowed to modify the value of a <code>const</code> variable, which is the danger of casting away the <code>const</code>ness of something: you better <em>know</em> it's not really <code>const</code>.</p> <p>The compiler, seeing that <code>maxint</code> is <code>const</code> and should <em>never</em> be modified, doesn't even have to give it an address. It can just replace all the uses of <code>maxint</code> with 100 if it sees fit. Also it might just put the constant in to a portion of memory that is read-only, as Matteo Italia points out, which is probably what's happening for you. That's why modifying it produces undefined behaviour.</p> <p>The only way you can safely cast away the <code>const</code>ness of a variable is if the variable is not actually <code>const</code>, but the <code>const</code> qualifier was added to a non-<code>const</code> variable, like this:</p> <pre><code>int f(const int&amp; x) { int&amp; nonconst = const_cast&lt;int&amp;&gt;(x); ++nonconst; } int blah = 523; f(blah); // this is safe const int constblah = 123; f(constblah); // this is undefined behaviour </code></pre> <p>Think about this example, which compiles perfectly:</p> <pre><code>int f(const int&amp; x) { int&amp; nonconst = const_cast&lt;int&amp;&gt;(x); ++nonconst; } int main() { f(4); // incrementing a number literal??? } </code></pre> <p>You can see how using <code>const_cast</code> is pretty dangerous because there's no way to actually tell whether a variable is originally <code>const</code> or not. You should avoid using <code>const_cast</code> when possible (with functions, by just not accepting <code>const</code> parameters).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload