Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Switches, default, and enums
#1
Rule 15.3 requires every switch to end with a default clause. While this is usually a good idea, it undermines the technique of using enums for switch control and having the compiler catch unused or unhandled values. For example:

Code:
typedef enum {
      red,
      green,
      blue
   } color_t;

   void f(color_t color) {
      switch (color) {
      case red:
         /* do something */
         break;
      case green:
         /* do something */
         break;
   }
Many compilers and certainly most lints will generate a warning when compiling the function f noting that not all enum values are handled. When the typedef and the switch are in different files, this can be quite helpful. When the enum is handled by switches in multiple source files, this structure allows the compiler to catch unmodified switches when a new enum value is added. If there was a default case in this switch, the compiler would not complain.

With that in mind, I suggest that rule 15.3 be revised by adding, \"except where the switch expression is an enum\" to the end. I might also add a advisory rule encouraging switch expressions to be enums.

Any thoughts?


Messages In This Thread

Forum Jump:


Users browsing this thread: 2 Guest(s)