I have legacy code that is using an enum as a range and iterating through the range. I need to port this to a new platform and make it safer.
Note: enums are not safe to iterate through as there may be “holes” or gaps between values.
I’m looking for a safe C language pattern for a range type.
For example, given a range (RED, VIOLET, BLUE, GREEN, YELLOW, ORANGE), I want to iterate through each value, like “FOR color IN (RED, VIOLET, BLUE, GREEN, YELLOW, ORANGE)”.
When I search SO and the web, I get replies about the range of a data type, such as the range of an integer.
This code will reside on an embedded system that uses an ARM7 processor.
An enum can do just fine, as long as you let the compiler choose values. This way, there would be no holes. You could, for example, do this:
And a quote from the ANSI C standard: