Versions Compared

Key

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

...

Include Page
c:MSC01 CS switch
c:MSC01 CS switch

Non-Compliant Code Example

This example fails to test for conditions where a is neither b nor c. This may be the correct behavior in this case, but failure to account for all the values of a may result in logic errors if a unexpectedly assumes a different value.

Code Block

...
if (a == b) {
  ...
}
else if (a == c) {
  ...
}
...

Compliant Solution

This compliant solution explicitly checks for the unexpected condition and handles it appropriately.

Code Block

...
if (a == b) {
  ...
}
else if (a == c) {
  ...
}
else {
  /* handle error condition */
}
...

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 widget_type may result in logic errors if 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 accidentally 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 (widget_type) {
  case WE_X: 
    ...
    break;
  case WE_Y: 
    ...
    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 by 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 (widget_type) {
  case WE_X: 
    ...
    break;
  case WE_Y: 
    ...
    break;
  case WE_Z: 
    ...
    break;
  default:
    /* handle error condition */
    break;
}   
...

References

Hatton 95 Section 2.7.2 Errors of omission and addition