I would expect the following code snippet to complain about trying to assign something other that 0,1,2 to a Color variable.
But the following does compile and I get the output
Printing:3
3
Can anybody explain why? Is enum not meant to be a true user-defined type? Thanks.
enum Color { blue=0,green=1,yellow=2};
void print_color(Color x);
int main(){
Color x=Color(3);
print_color(x);
std::cout << x << std::endl;
return 0;
}
void print_color(Color x)
{
std::cout << "Printing:" << x << std::endl;
}
Since you manually cast the
3toColor, the compiler will allow you to do that. If you tried to initialize the variablexwith a plain3without 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:The value
3is thus still in range, and so the code is valid. Had you cast a4, 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 to127. But as mentioned, the compiler is not required to convert a4to a value of4, 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