Home >Backend Development >C++ >What Happens When Casting an Invalid Value to an Enum Class in C ?

What Happens When Casting an Invalid Value to an Enum Class in C ?

DDD
DDDOriginal
2024-12-24 20:22:12368browse

What Happens When Casting an Invalid Value to an Enum Class in C  ?

Impact of Casting Invalid Value to Enum Class

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.

CWG 1766: A Change in Behavior

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.

Integral Promotions in Switch Statements

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.

Caution with Unscoped Enumerations

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn