Rule 15.3 - question over wording of rule

6.15 Switch Statements

Moderators: misra-c, david ward

Post Reply
CarlinB
Posts: 1
Joined: Tue Feb 15, 2005 3:02 pm
Location: Michigan

Rule 15.3 - question over wording of rule

Post by CarlinB » Thu Apr 02, 2009 12:53 am

Hello,

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.

Code: Select all

switch(itemSelected)
{
    default:
    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.

misra-c
Posts: 560
Joined: Thu Jan 05, 2006 1:11 pm

Re: Rule 15.3 - question over wording of rule

Post by misra-c » Tue Apr 07, 2009 5:04 pm

This is being considered and has been assigned tracker ID 0000021.
---
Posted by and on behalf of
the MISRA C Working Group

Post Reply

Return to “6.15 Switch Statements”