C - Data Type Enum

Introduction

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 in this instance, follows the enum keyword.

Variables of type Weekday can have any of the values listed.

These names are called enumeration constants or enumerators.

Each enumeration constant is identified by the unique name you assign, and the compiler will assign a value of type int to each name.

An enumeration is an integer type, and the enumerators 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.

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.

Wednesday will correspond to the value 2.

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.

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

You could write the previous statement like this:

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

Related Topics