c++ warning: enumeration value not handled in switch [-Wswitch]

落爺英雄遲暮 提交于 2019-12-05 00:13:47

Be explicit

It depends on what you are trying to achieve. The governing rule is

It is better to be explicit.

Omitting the cases simply makes it look like you forgot some. Being explicit assures subsequent readers of your code that you intended to do nothing for certain events.

In light of that, you have a couple of options:

Option 1 - add the default

default:
  break;

This suppresses the warning, and makes it clear that you don't intend to handle the other event types here.

Option 2 - list each value

List each event type, followed by a break. This is also explicit, and has the added bonus that, should you ever add an event type, the compiler will once again warn you that your switch is incomplete. This can be valuable when you have many switch statements, some of which need to be modified to do something new when an enum value is added.

What about a series of if statements?

I would not recommend using a series of if statements here. A switch is clearer, reduces the amount of typing, and (as you've seen) can produce better compiler warnings for cases you omitted.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!