Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Since you manually cast the <code>3</code> to <code>Color</code>, the compiler will allow you to do that. If you tried to initialize the variable <code>x</code> with a plain <code>3</code> without a cast, you would get a diagnostic. </p> <p>Note that the range of values an enumeration can store is not limited by the enumerators it contains. It's the range of values of the smallest bitfield that can store all enumerator values of the enumeration. That is, the range of your enumeration type is <code>0..3</code>:</p> <pre><code>00 01 10 11 </code></pre> <p>The value <code>3</code> is thus still in range, and so the code is valid. Had you cast a <code>4</code>, then the resulting value would be left unspecified by the C++ Standard. </p> <p>In practice, the implementation has to chose an underlying integer type for the enumeration. The smallest type it can choose is <code>char</code>, but which is still able to at least store values ranging up to <code>127</code>. But as mentioned, the compiler is not required to convert a <code>4</code> to a value of <code>4</code>, because it's outside the range of your enumeration. </p> <hr> <p>I figure i should post some explanation on the difference of "underlying type" and "range of enumeration values". The range of values for any type is the smallest and largest value of that type. The underlying type of an enumeration must be able to store the value of any enumerator (of course) - and two enumerations that have the same underlying type are layout compatible (this allows some flexibility in case a type mismatch occurs). </p> <p>So while the underlying type is meant to fix the object representation (alignment and size), the values of the enumeration is defined as follows in <code>7.2/6</code></p> <blockquote> <p>For an enumeration where e<sub>min</sub> is the smallest enumerator and e<sub>max</sub> is the largest, the values of the enumeration are the values of the underlying type in the range b<sub>min</sub> to b<sub>max</sub>, where b<sub>min</sub> and b<sub>max</sub> are, respectively, the smallest and largest values of the smallest bit-field that can store e<sub>min</sub> and e<sub>max</sub> . It is possible to define an enumeration that has values not defined by any of its enumerators.</p> <p>[Footnote: On a two’s-complement machine, b<sub>max</sub> is the smallest value greater than or equal to <code>max (abs(</code>e<sub>min</sub><code>) − 1 ,abs(</code>e<sub>max</sub><code>))</code> of the form 2<sup>M</sup>−1; b<sub>min</sub> is zero if e<sub>min</sub> is non-negative and <code>−(</code>b<sub>min</sub><code>+1)</code> otherwise.]</p> </blockquote>
 

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