Enumeration Constants

When you define an enumeration data type, you specify a set of identifiers that the data type represents. Each identifier in this set is an enumeration constant.

The value of the 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 constant. The identifier represents the value of the constant expression.
  2. If no explicit value is assigned, the leftmost constant in the list receives the value zero (0).
  3. Identifiers with no explicitly assigned values receive the integer value that is one greater than the value represented by the previous identifier.

C In C, enumeration constants have 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. Use an enumeration constant anywhere an integer constant is allowed, or for C++, anywhere a value of the enumeration type is allowed.

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

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

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       */

Related References

IBM Copyright 2003