Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Switches, default, and enums
#2
ChrisNelson Wrote:Rule 15.3 requires every switch to end with a default clause. [...] 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. [...]
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?

While I have some sympathy with this position, we have to realise that enums are just ints beneath, and there's nothing much to stop you writing

Code:
f((color_t) -1);

so we have to balance the static checking offered by the lint against the dynamic checking available through a suitable default case.

One possibility might be to hide the default case from the lint; although this would bring up another set of issues needing justification.

As usual, where there is some debate in the issue, it is probably best if you raise a deviation to the rule containing your proviso ("except where the switch expression is an enum") with appropriate justification.

stephen


Messages In This Thread

Forum Jump:


Users browsing this thread: 1 Guest(s)