Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
9.4.2 - Why C-style enums are exempted from requiring a default clause?
#1
Rule 9.4.2 requires that all switch blocks have a "default" case, for defensive programming.

This is however not required when using C-style enums, i.e. unscoped and without underlying type. Presumably because it's Undefined Behavior to cast an int out-of-range to a C-style enum, whereas it's well-defined behavior for "C++ enums". Since UB is assumed to not happen, one can assume that a C-style enum has a valid value.

However, there's a subtlety. The "range" of a C-style enum is not just the list of valid enumerators, but the smallest bitset that contains all enumerators.

So for example:

Code:
enum Foo
{
   a = 0,
   b = 1,
   c = 2,
   d = 3
};

The following code is **not** Undefined Behavior, because the valid range of this enum is 0-7 (2^3 - 1).

Code:
enum Foo x = static_cast<Foo>(7);

So I'd argue that defensive programming still applies here and a "default" case would still be needed.

What do you think?
Reply
#2
The problem with your example is that it already violates 10.2.3, so the question of whether it violates this rule as well is moot.
Posted by and on behalf of
the MISRA C++ Working Group
Reply
#3
(02-09-2024, 02:12 PM)misra cpp Wrote: The problem with your example is that it already violates  10.2.3, so the question of whether it violates this rule as well is moot.

Fair enough. However, one could think of receiving said enum from an external C library, where we don't have control over how that enum is created. Wouldn't it still make sense to be defensive about those types of errors?
Reply
#4
Short answer, yes.  Ideally, all your code should be MISRA compliant, so the values you get from the external library should already obey the rules for enum types. 

If you are using libraries that are not MISRA compliant, then you should be treating any values they return with suspicion, and use defensive coding to ensure the values have the expected properties - like enums not having undeclared values.
Posted by and on behalf of
the MISRA C++ Working Group
Reply


Forum Jump:


Users browsing this thread: 3 Guest(s)