15.2 and 'break's inside if-else

6.15 Switch Statements

Moderators: misra-c, david ward

Post Reply
gs
Posts: 87
Joined: Thu Nov 18, 2004 1:39 am

15.2 and 'break's inside if-else

Post by gs » Thu Sep 06, 2012 8:26 pm

Suppose I have the following code:

Code: Select all

...
switch( x )
{
case 1:
    if( y )
        {
        ...
        break;
        }
    else
        {
        ...
        break;
        }
default:
    break;
}
...
Does this code violate rule #15.2?

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

Re: 15.2 and 'break's inside if-else

Post by misra-c » Thu Sep 13, 2012 5:36 pm

Yes, this does violate Rule 15.2 because the break statements are conditionally-executed, even though there is a break on both paths from the case label. The headline requires an unconditional break.

The normative rationale also states that the last statement in every switch clause shall be break statement or, if the last statement is a compound statement then break shall be the last statement in that compound statement. In the example given, the last statement in the switch clause is the if statement.

Finally, the syntax given in Rule 15.0, which supports all the rules in this section, is clear that the break statement must be the final, unconditionally-executed statement in a switch clause.
---
Posted by and on behalf of
the MISRA C Working Group

gs
Posts: 87
Joined: Thu Nov 18, 2004 1:39 am

Re: 15.2 and 'break's inside if-else

Post by gs » Tue Oct 09, 2012 3:17 pm

Does this hold true even if, instead of an if-else, the case region contains an unconditional 'return'?

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

Re: 15.2 and 'break's inside if-else

Post by misra-c » Tue Oct 16, 2012 5:55 pm

Yes, the break statement must be present even if preceded by a return statement.

Using a return statement in this way will break Rule 14.7. There is then a choice of using the break statement, thereby violating Rule 14.1, or omitting it and violating Rule 15.2.

Either way will violate two rules.
---
Posted by and on behalf of
the MISRA C Working Group

staffann
Posts: 1
Joined: Wed Nov 25, 2015 8:01 am
Company: Prevas

Re: 15.2 and 'break's inside if-else

Post by staffann » Mon Dec 14, 2015 7:19 am

Maybe I shouldn't continue this old thread, but here it goes.

I would have prefered if the MISRA rules were more separated so that a deviation could be limited to one rule. The rule 14.7 is nice but should ideally not be enforced by rule 15.2. If 15.2 had said that no fallthrough is allowed (better formulated of course) rather than that a break statement is necessary then this separation would have been achieved.

Post Reply

Return to “6.15 Switch Statements”