Value of an out-of-range enum
suggest changeIf a scoped enum is converted to an integral type that is too small to hold its value, the resulting value is unspecified. Example:
enum class E {
X = 1,
Y = 1000,
};
// assume 1000 does not fit into a char
char c1 = static_cast<char>(E::X); // c1 is 1
char c2 = static_cast<char>(E::Y); // c2 has an unspecified value
Also, if an integer is converted to an unscoped enumeration whose underlying type is not fixed, and the integer is outside the range of that enumeration, the result is unspecified before C++17 and the behavior is undefined since C++17. For Color, that range is the values of the smallest bit-field that can hold 1 and 3, which is 0 through 3, so 4 is outside it. Example:
enum Color {
RED = 1,
GREEN = 2,
BLUE = 3,
};
Color c = static_cast<Color>(4);
However, in the next example, the behavior is not unspecified, since the source value is within the range of the enum, although it is unequal to all enumerators:
enum Scale {
ONE = 1,
TWO = 2,
FOUR = 4,
};
Scale s = static_cast<Scale>(3);
Here s will have the value 3, and be unequal to ONE, TWO, and FOUR.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents