Page 1 of 1

15.2 and 'break's inside if-else

Posted: Thu Sep 06, 2012 8:26 pm
by gs
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?

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

Posted: Thu Sep 13, 2012 5:36 pm
by misra-c
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.

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

Posted: Tue Oct 09, 2012 3:17 pm
by gs
Does this hold true even if, instead of an if-else, the case region contains an unconditional 'return'?

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

Posted: Tue Oct 16, 2012 5:55 pm
by misra-c
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.

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

Posted: Mon Dec 14, 2015 7:19 am
by staffann
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.