Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
10.5 Iterating over an enum
#1
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?
<t>Dermot</t>
Reply
#2
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:
typedef enum { EA =1, EB = 3, ELAST = 5 } en1;
An alternative way of writing the loop would be
Code:
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
Reply
#3
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.
<t>Dermot</t>
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)