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 enum and the integer’s value is outside the range of the enum’s values, the resulting value is unspecified. 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