Cro: Maintain it With Zig
Cro: Maintain it With Zig
Posted Sep 12, 2021 22:19 UTC (Sun) by excors (subscriber, #95769)In reply to: Cro: Maintain it With Zig by HelloWorld
Parent article: Cro: Maintain it With Zig
"enum class Foo" is a scoped enumeration so it does have a fixed underlying type (defaulting to int), per C++20 9.7.1.5:
> Each enumeration defines a type that is different from all other types. Each enumeration also has an underlying type. The underlying type can be explicitly specified using an enum-base. For a scoped enumeration type, the underlying type is int if it is not explicitly specified. In both of these cases, the underlying type is said to be fixed.
The undefined behaviour only applies to an unscoped enum with no explicitly specified underlying type. And in that case "the range of the enumeration values" is not just the list of declared enumerators, it's a power-of-two-aligned range that includes the list of enumerators, per C++20 9.7.1.8:
> For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type. Otherwise, the values of the enumeration are the values representable by a hypothetical integer type with minimal width M such that all enumerators can be represented. [...] It is possible to define an enumeration that has values not defined by any of its enumerators
(C++17 has a much more verbose definition but I think it has the same effect.)
> Again, what are you going to do about it when you encounter a value other than the enumerators?
If that case can only be triggered by a bug in your code, you could do the equivalent of assert(0), i.e. crash the process and let some other system (init, kernel, hardware watchdog, etc) recover cleanly - same as any other case where you detect a bug. That's safer than e.g. falling off the bottom of a non-void function and returning some garbage (which could be a security vulnerability).
> Anyway, the whole enum situation in C++ is a bit of a mess.
I can't disagree with that :-)
