MISRA Discussion Forums

Full Version: Rule 15.3 - question over wording of rule
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

Rule 15.3 states that "The final clause of a switch statement shall be the default clause."

Is the point of the rule to dictate where the default clause should be located or only to make sure that every switch statement includes a default clause?

I would agree that every switch statement should have a default clause, but I am not clear on why the rule would dictate where this clause should be located.

The rule description clearly states this is a "defensive programming" action. Being such, it makes sense that many times the end of your clause list is the appropriate place for the default clause (there to catch any unhandled case). However, there are times where the desired default behavior is the same as one of the case clauses. Furthermore, the arrangement of the case clauses is often done in some logical order (i.e. progression through a menu). It seems to me that reordering the list of cases just to satisfy this rule is unnecessary, particularly when it breaks the logical flow of the cases.

As an example, here is a switch statement that might be used to determine the appearance of a list of items displayed to a user. For this example, the desired default behavior is to display the list same as if "case 0" was the selection.

    case 0:  
    {  /* show list with first item highlighted */ } break;

    case 1:
    {  /* show list with second item highlighted */ } break;

    case n:
    {  /* show list with n-th item highlighted */ } break;

Logically, I feel it makes more sense to locate the default clause with the first case clause rather than moving "case 0" to the end of the clause list or repeating the contents of the "case 0" clause in the default clause.

I realize that in practice a deviation can be recorded for why this rule is not followed. But, if the real intent of the rule is to ensure a default clause is always provided then it seems the rule should be reworded to emphasize the need for a default clause and leave the location of the default clause as advisory. However, if the rule really is meant to dictate where the default clause is located, I would appreciate if someone could provide an explanation of why this location is important enough to be a "required" rule.
This is being considered and has been assigned tracker ID 0000021.