MISRA Discussion Forums
10.5 Iterating over an enum - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C (https://forum.misra.org.uk/forumdisplay.php?fid=4)
+--- Forum: MISRA C:2012 and MISRA C:2023 guidelines (https://forum.misra.org.uk/forumdisplay.php?fid=21)
+---- Forum: 8.10 The essential type model (https://forum.misra.org.uk/forumdisplay.php?fid=165)
+---- Thread: 10.5 Iterating over an enum (/showthread.php?tid=1209)



10.5 Iterating over an enum - dermiem - 29-10-2015

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?


Re: 10.5 Iterating over an enum - misra-c - 26-11-2015

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.


Re: 10.5 Iterating over an enum - dermiem - 26-11-2015

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.