Using default in a switch statement when switching over an enum

后端 未结 16 1293
一个人的身影
一个人的身影 2020-12-15 02:57

What is your procedure when switching over an enum where every enumeration is covered by a case? Ideally you\'d like the code to be future proof, how do you do that?

<
16条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 03:57

    As an additional remark (in addition to other responses) I'd like to note that even in C++ language with its relatively strict type-safety restrictions (at least compared to C), it is possible to generate a value of enum type that in general case might not match any of the enumerators, without using any "hacks".

    If you have a enum type E, you can legally do this

    E e = E();
    

    which will initialize e with zero value. This is perfectly legal in C++, even if the declaration of E does not include a enumeration constant that stands for 0.

    In other words, for any enum type E, the expression E() is well-formed and generates zero value of type E, regardless of how E is defined.

    Note, that this loophole allows one to create a potentially "unexpected" enum value without using any "hacks", like a cast of an int value to enum type you mentioned in your question.

提交回复
热议问题