TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
ASML C Coding Standard
Search

Rule:  6.2.5.aChecked automatically with code checker

Synopsis:One must not rely on the actual numerical value of an enum variable.
Language:C
Severity Level:6
Category:Concepts


Description:

Justification

The representation of enum types should not be relied upon, because this representation can change when adding or removing items in the enum. One can iterate through an enum, but calculations with enum values are not allowed. The language doesn't make that difference, so it is left to the programmer to inspect the messages as relevant. Two kinds of enumerations can be used in loops:

  • Enumerations with a start and finish that are not part of the enumeration itself, e.g. { COLOR_START, RED, YELLOW, BLUE, COLOR_END }
  • Enumerations with a start and finish that are part of the enumeration itself, e.g. { RED, YELLOW, BLUE }

Example 1

typedef enum number_enum_tag
{
   ONE = 1,
   TWO,
   THREE,
   FOUR
} number_enum;

number_enum n;
int fac = 1;

for (n = ONE; n <= FOUR; n++) /* RIGHT */
{
   fac *= n; /* WRONG */
}

Example 2

typedef enum color_enum_tag
{
   COLOR_START = 0,
   RED,
   YELLOW,
   BLUE,
   COLOR_END
} color_enum; 

typedef enum color1_enum_tag
{
   RED1 = 0,
   YELLOW1,
   BLUE1
} color1_enum;

color_enum enumvar;
color1_enum enumvar1;

for (enumvar = COLOR_START; enumvar < COLOR_END; enumvar++) /* RIGHT */
{
}

for (enumvar1 = RED1; enumvar1 <= BLUE1; enumvar1++) /* RIGHT */
{
}