Using default in a switch statement when switching over an enum

后端 未结 16 1261
一个人的身影
一个人的身影 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:41

    In cases similar to the example provided you can actually combine option 1 with one of the other options: Omit the default and enable the appropriate compiler warning if available. This way you find out immediately if a new enumerated value is added and you can conveniently add the case without having to guarantee that a specific code path executes to find it at runtime.

    Then between the end of the switch and the end of the function add code to assert or throw (I prefer assert as this really is an invalid situation). This way if someone casts an int to your enum type you still get the runtime checking as well.

提交回复
热议问题