Since you manually cast the 3
to Color
, the compiler will allow you to do that. If you tried to initialize the variable x
with a plain 3
without a cast, you would get a diagnostic.
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 0..3
:
00
01
10
11
The value 3
is thus still in range, and so the code is valid. Had you cast a 4
, then the resulting value would be left unspecified by the C++ Standard.
In practice, the implementation has to chose an underlying integer type for the enumeration. The smallest type it can choose is char
, but which is still able to at least store values ranging up to 127
. But as mentioned, the compiler is not required to convert a 4
to a value of 4
, because it's outside the range of your enumeration.
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).
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 7.2/6
For an enumeration where emin is the smallest enumerator and emax is the largest, the values of the enumeration are the values of the underlying type in the range bmin to bmax, where bmin and bmax are, respectively, the smallest and largest values of the smallest bit-field that can store emin and emax . It is possible to define an enumeration that has values not defined by any of its enumerators.
[Footnote: On a two’s-complement machine, bmax is the smallest value greater than or equal to max (abs(
emin) − 1 ,abs(
emax))
of the form
2M−1; bmin is zero if emin is non-negative and −(
bmin+1)
otherwise.]