Home >Backend Development >C++ >What Happens When Casting an Invalid Value to an Enum Class in C ?
Consider the code snippet:
enum class Color : char { red = 0x1, yellow = 0x2 }; char *data = ReadFile(); Color color = static_cast<Color>(data[0]);
What happens when data[0] is 100? According to the C 11 and C 14 Standards, the resulting value is unspecified, meaning it could be anything.
However, after CWG 1766, casting a value outside the range of the enumeration to the enum type can now invoke Undefined Behavior (UB). This change only affects compiler implementations that choose to apply the defect to their C 11 and C 14 compilation modes.
In a switch statement, the condition is converted to an integral type. For unscoped enumerations, this conversion applies to integers; for scoped enumerations (enum class and enum struct), no promotion occurs. Regardless, the condition value is within the range of the underlying type and int, so the default label should still be hit.
For enums without a fixed underlying type, casting values outside the range may result in unspecified behavior (prior to CWG 1766) or UB (after CWG 1766). This is illustrated with the enum ColorUnfixed:
enum ColorUnfixed { red = 0x1, yellow = 0x2 };
Since the underlying type is not fixed, the range of ColorUnfixed is from 0 to 3, making 100 an invalid value.
The above is the detailed content of What Happens When Casting an Invalid Value to an Enum Class in C ?. For more information, please follow other related articles on the PHP Chinese website!