Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Non-Compliant Code Example

This non-compliant code example fails to consider all possible cases. This may be the correct behavior in this case, but failure to account for all the values of a widget_type may result in logic errors if a widget_type unexpectedly assumes a different value. This is particularly problematic in C, because an identifier declared as an enumeration constant has type int. Therefore, a programmer can accidently assign an arbitrary integer value to an enum type as shown in this example.

Code Block
...
enum WidgetEnum { WE_W, WE_X, WE_Y, WE_Z } widget_type;

widget_type = 45; 
  
switch (awidget_type) {
  case WE_X: 
    ...
    break;
  case WE_Y: 1 
    ...
    break;
  case WE_Z: 
    ...
    break;
}   
...

Implementation Details

Microsoft Visual C++ .NET with /W4 does not warn when assigning an integer value to an enum type, or when the switch statement does not contain all possible values of the enumeration.

Compliant Solution

This compliant solution explicitly checks for the unexpected condition and handles it appropriatelyby adding a default clause to the switch statement.

Code Block
...
enum WidgetEnum { WE_X, WE_Y, WE_Z } widget_type;

widget_type = WE_X; 
  
switch (awidget_type) {
  case WE_X: 1 
    ...
    break;
  case WE_Y: 
    ...
    break;
  case WE_Z: 
    ...
    break;
  default:
    assert(0);
    abort();
    break;
}   
...

References

Hatton 95 Section 2.7.2 Errors of omission and addition