Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
9.4.2 - Requirement about the default clause
#1
Hi,

Rule 9.4.2 requires every switch statement to have a default clause, to match handling of if/else. However, unlike an if/else statement, this has a very serious implication: it prevents the compiler from warning about explicitly unhandled enumerators:

Code:
enum class Enum
{
  A,
  B,
  C  // newly added
};

// some client code, far away from the Enum declaration
int process(Enum e)
{
  switch(e)
  {
    case Enum::A: { return 123; }
    case Enum::B: { return 321; }
    // Oops, client code does not realize they should handle Enum::C, compiler didn't warn!
    default: { return 0; }
  }
}

One could put a runtime assertion in the `default` clause, but it only shifts the problem to the right. A problem that would have been caught at compile time can now only be caught at runtime. We should catch as many defects as possible at compile time.

One can also enable -Wswitch-enum, but this is not always desirable. Sometimes one explicitly wants the switch to be non-exhaustive, and can express that via the "default" clause. With the warning, one needs to introduce non-compliant inline suppressions with compiler-specific pragmas. Or one must explicitly list all the unwanted labels and fall-through the default case, polluting the code with non-interesting code paths.

Here we are balancing two risks:

1. The risk of not handling a valid enumerator (as above).
2. The risk of not handling an non-enumerator int casted into an Enum (as per the Rationale), in the spirit of defensive programming.

Questions: has Risk 1 been considered by MISRA? Is there evidence suggesting that Risk 2 is more likely to happen than Risk 1, and we should therefore prioritize it instead?

Thanks!
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)