Implicit type conversions in switch statements

6.15 Switch Statements

Moderators: misra-c, david ward

Post Reply
Posts: 7
Joined: Fri Oct 07, 2005 7:46 pm
Company: Escher Technologies Ltd.
Location: Ash Vale, Surrey, UK

Implicit type conversions in switch statements

Post by dcrocker » Tue Nov 02, 2010 5:48 pm

I've a question concerning the following example:

Code: Select all

int8 x;
    case 0:      /* valid */
    case 255:    /* valid? */
    case 1L:     /* invalid, implicit cast from long to int */
I would expect any good static checker to report that x can never equal 255 here. But is 'case 255:' actually a MISRA 2004 rule violation? The C standard says that the switch expression x gets promoted to 'int' in this case, so the type of the case label 255 does match the type of the promoted switch expression. I can't find any MISRA rule that says that we should consider the underlying type (instead of the promoted type) of the switch variable when deciding whether a case label is allowed or not. If "case 255:" was the only case label on some code, then rule 14.1 (no unreachable code) would apply; but in this example, there is no unreachable code.
David Crocker
Escher Technologies Ltd.

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

Re: Implicit type conversions in switch statements

Post by misra-c » Wed Nov 03, 2010 9:22 am

The underlying type of the controlling expression of the switch statement is signed 8-bit.

Conversion of 1L from underlying long int to signed 8-bit violates Rule 10.1.

Conversion of 255 from underlying signed 16-bit to signed 8-bit also violates Rule 10.1.

This conversion is mentioned in Section 6.10.2 under the subsection Assigning Conversions. See also the Exemplar Suite file mc2_1001.c.
Posted by and on behalf of
the MISRA C Working Group

Post Reply

Return to “6.15 Switch Statements”