10.5 Iterating over an enum

Moderators: misra-c, david ward

Post Reply
dermiem
Posts: 2
Joined: Mon Oct 18, 2004 8:42 am
Location: Yazaki

10.5 Iterating over an enum

Post by dermiem » Thu Oct 29, 2015 4:32 pm

I usually define a enum in a project specific H file, to represent a set of signals:
typedef enum {
ADC_VBAT
ADC_FEEDBACK,
ADC_VOLTAGE,

ADC_NUM_SIGNALS
} adc_t ;

And then in the reusable C file, iterate over the configured set of signals. For example, to set the initial value of the averaged signal:

uint8_t i ;

for (i=0U; i < (uint8_t) ADC_NUM_SIGNALS; i++)
{
AdcClearAverage((adc_t) i) ;
}

where AdcClearAverage takes a parameter of type adc_t.

But this now generates warning 10.5 as an unsigned type is being cast to an enum.
What is the correct way to iterate over an enumeration?
Dermot

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

Re: 10.5 Iterating over an enum

Post by misra-c » Thu Nov 26, 2015 10:21 am

Iterating over an enumeration is non-compliant with MISRA C:2012, because in general it is not known that all values in the iteration loop exist as enumeration values. For example

Code: Select all

 typedef enum { EA =1, EB = 3, ELAST = 5 } en1;
An alternative way of writing the loop would be

Code: Select all

  for ( adc_t en = ADC_VBAT; en < ADC_NUM_SIGNALS; en++ )
  {
    AdcClearAverage( en ) ;
  }
but this does violate rule 10.1 as ++ is not allowed on objects with an enumeration type.

Both the original and the alternative way of writing the loop would require a deviation. The deviation would need to include the information that
  • 1. The enumeration type contained no gaps in the numbering sequence
    2. The start and end points of the loop were members of the enumeration type
In addition you might also want to state that the start/end points of the loop are the first and last members of the enumeration type.
---
Posted by and on behalf of
the MISRA C Working Group

dermiem
Posts: 2
Joined: Mon Oct 18, 2004 8:42 am
Location: Yazaki

Re: 10.5 Iterating over an enum

Post by dermiem » Thu Nov 26, 2015 10:52 am

Thank you for the reply.
It is disappointing that the standard does not allow iteration over an enum which has no gaps (as this is testable using a static analysis tool).
Relaxing this rule in future updates to the standard, to allow casting between an integer and a gap free enum, would be very useful.
Dermot

Post Reply

Return to “8.10 The essential type model”