Enumeration members

The list of enumeration members, or enumerators, provides the data type with a set of values.

Read syntax diagramSkip visual syntax diagramEnumeration member declaration syntax
 
>>-identifier--+-------------------------+---------------------><
               '-=--enumeration_constant-'
 

C only In C, an enumeration constant is of type int. If a constant expression is used as an initializer, the value of the expression cannot exceed the range of int (that is, INT_MIN to INT_MAX as defined in the header limits.h).

C++ In C++, each enumeration constant has a value that can be promoted to a signed or unsigned integer value and a distinct type that does not have to be integral. You can use an enumeration constant anywhere an integer constant is allowed, or anywhere a value of the enumeration type is allowed.

The value of an enumeration constant is determined in the following way:

  1. An equal sign (=) and a constant expression after the enumeration constant gives an explicit value to the enumeration constant. The enumeration constant represents the value of the constant expression.
  2. If no explicit value is assigned, the leftmost enumeration constant in the list receives the value zero (0).
  3. Enumeration constants with no explicitly assigned values receive the integer value that is one greater than the value represented by the previous enumeration constant.

The following data type declarations list oats, wheat, barley, corn, and rice as enumeration constants. The number under each constant shows the integer value.

enum grain { oats, wheat, barley, corn, rice };
   /*         0      1      2      3     4         */

enum grain { oats=1, wheat, barley, corn, rice };
   /*         1        2      3      4     5       */

enum grain { oats, wheat=10, barley, corn=20, rice };
   /*          0     10        11     20       21  */

It is possible to associate the same integer with two different enumeration constants. For example, the following definition is valid. The identifiers suspend and hold have the same integer value.

enum status { run, clear=5, suspend, resume, hold=6 };
   /*          0      5        6       7       6       */

Each enumeration constant must be unique within the scope in which the enumeration is defined. In the following example, the second declarations of average and poor cause compiler errors:

func()
    {
       enum score { poor, average, good };
       enum rating { below, average, above };
       int poor;
    }

Related information



[ Top of Page | Previous Page | Next Page | Contents | Index ]