by _cbsz · 4y ago · 0 comments
If you don't set the underlying type, assigning a value that doesn't match an enumerator via `static_cast` is undefined behavior. See https://en.cppreference.com/w/cpp/language/enum . (Doing weird pointer casting things is also undefined behavior per the strict aliasing rule, though, come to think of it, I'm not sure whether memcpying an out-of-range value into an enum through the "reinterpret_cast to `char*`" loophole is undefined behavior.)
> If the underlying type is not fixed and the source value is out of range, the behavior is undefined.
Note the fine print about the meaning of ”out of range”:
> (The source value, as converted to the enumeration's underlying type if floating-point, is in range if it would fit in the smallest bit field large enough to hold all enumerators of the target enumeration.)
So this is not undefined:
enum E { A = 0, B = 1, C = 2 };
E valid = static_cast<E>(3);Choosing one just makes a difference because code has problems.