Hacker News new | ask | show | jobs
by _cbsz 1468 days ago
> you can't trust that your enums have a value inside their interval

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.)

2 comments

I’m assuming you are referring to this part:

> 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);
Ugh. You are right, and that's sad.
Even if that covered all the problem space (instead of replacing it with a much larger one), if your code is flawless, parsing and validating are equivalent.

Choosing one just makes a difference because code has problems.