MISRA Discussion Forums
9.4.2 - Why C-style enums are exempted from requiring a default clause? - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C++ (https://forum.misra.org.uk/forumdisplay.php?fid=18)
+--- Forum: MISRA C++:2023 guidelines (https://forum.misra.org.uk/forumdisplay.php?fid=188)
+---- Forum: 4.9 Statements (https://forum.misra.org.uk/forumdisplay.php?fid=195)
+---- Thread: 9.4.2 - Why C-style enums are exempted from requiring a default clause? (/showthread.php?tid=1699)



9.4.2 - Why C-style enums are exempted from requiring a default clause? - cgpzs - 22-08-2024

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?


RE: 9.4.2 - Why C-style enums are exempted from requiring a default clause? - misra cpp - 02-09-2024

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.


RE: 9.4.2 - Why C-style enums are exempted from requiring a default clause? - cgpzs - 03-09-2024

(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?


RE: 9.4.2 - Why C-style enums are exempted from requiring a default clause? - misra cpp - 13-09-2024

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.