6.2 and switch/case labels

6.6 Types

Moderators: misra-c, david ward

Post Reply
dreser
Posts: 1
Joined: Wed Mar 27, 2013 12:10 pm
Company: Sensor-Technik Wiedemann GmbH

6.2 and switch/case labels

Post by dreser » Tue Mar 11, 2014 4:44 pm

I'm not 100% sure on the interpretation of rule 6.2 when it comes to using "unsigned char" values as labels for switch case.

Example:

Code: Select all

const uint8_t CONSTANT_ONE = 12U;
const uint8_t CONSTANT_TWO = 34U;

uint8_t value = foo();

switch (value)
{
case CONSTANT_ONE:
  [...]
   break;
case CONSTANT_TWO:
  [...]
   break;
default:
  [...]
   break;
}
For each of the "case <constant>" lines PC-lint (from V9.00j on) complains about a "Disallowed use of non-numeric value in a case label".
I would have considered defining and using the contants as "storage and use of numeric values" as described in 6.2.
I also can not find a similar limitation in MISRA-C 2012. Though I might not have looked deeply enough as I only have it in printed form.

Thanks for any feedback you might have on this.

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

Re: 6.2 and switch/case labels

Post by misra-c » Fri Mar 21, 2014 3:07 pm

We shall divide our response into 3 sections.

1. This code contains a constraint error and so will violate Rule 1.1. Both C90 6.6.4.2 and C99 6.8.4.2(3) list in their constraint section that the case label "shall be an integer constant expression". A const object is not an "integer constant expression" in C. The code would be compliant with C if the following had been used
#define CONSTANT_ONE 12U
It could be that this is what the PC-lint message is referring to, since CONSTANT_ONE in the original example is an object not a numeric value.

2. Assuming uint8_t has been defined as "unsigned char", there is no violation of 6.2 in this example. If uint8_t had been defined as plain "char", then rule 6.1 would have been violated in the initialisations of CONSTANT_ONE and CONSTANT_TWO.

3. MISRA-C:2004 rules 6.1 and 6.2 are covered by the essential type rules R.10.1 - R.10.8 of MISRA C:2012.
---
Posted by and on behalf of
the MISRA C Working Group

Post Reply

Return to “6.6 Types”