Learn C - C Enumerations






With an enumeration, you define a new integer type where variables of the type have a fixed range of possible values.

Here's an example of a statement that defines an enumeration type with the name Weekday:

enum Weekday {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};

This statement defines a type. The name of the new type, Weekday, follows the enum keyword, and this type name is referred to as the tag of the enumeration.

An enumeration is an integer type, and the enumerators that you specify will correspond to integer values.

By default the enumerators will start from zero, with each successive enumerator having a value of one more than the previous one.

In this example, the values Monday through Sunday will have values 0 through 6. You could declare a variable of type Weekday and initialize it like this:

enum Weekday today = Wednesday;

This declares a variable with the name today and it initializes it to the value Wednesday.

It is also possible to declare variables of the enumeration type when you define the type.

Here's a statement that defines an enumeration type plus two variables:

enum Weekday {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday} today, tomorrow;

This declares the enumeration type Weekday and two variables of that type, today and tomorrow.

Naturally you could also initialize the variable in the same statement, so you could write this:

enum Weekday {Monday, Tuesday, Wednesday, Thursday, 
                      Friday, Saturday, Sunday} today = Monday, tomorrow = Tuesday; 

Because variables of an enumeration type are of an integer type, they can be used in arithmetic expressions. You could write the previous statement like this:

  
enum Weekday {Monday, Tuesday, Wednesday, Thursday, 
              Friday, Saturday, Sunday} today = Monday, tomorrow = today + 1; 




Enumerator Values

You can specify your own integer value for any or all of the enumerators explicitly.

Although the names you use for enumerators must be unique, there is no requirement for the enumerator values themselves to be unique.

Here's how you could define the Weekday type so that the enumerator values start from 1:

enum Weekday {Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};

Now the enumerators Monday through Sunday will correspond to values 1 through 7.

The enumerators that follow an enumerator with an explicit value will be assigned successive integer values.

You could define an enumeration to identify card face values like this:

  
enum FaceValue { two=2, three, four, five, six, seven, 
                 eight, nine, ten, jack, queen, king, ace};