Enumeration in C

In this article, we would discuss enumeration in C. If we intend to have a variable, which stores value from a pre-defined set of values. Then, that is where enumerations comes in handy.

Enumerations are way to define data types. We can have both named as well as unnamed enumeration data types. We will discuss each of these with relevant examples next.

Named enumeration types

To illustrate a named enumeration declaration:

Example 1.

enum month
{
     January,
     February,
     March,
};

where,

enum month

defines a tagmonth, which is the data type. enum is the keyword.

{January, February, March}

Variable of data type month can have only these values i.e. January, February and March. These are referred to as enumerator constants.

To declare & initialize the variable of type month

enum month abc = february;

Here, variable is abc of data type month with value initialized as february.

Unnamed enumeration types

In this case, we don’t have a enumeration data type name –

Example 2.

enum 
{
     January,
     February,
     March,
} month;

Here, we have a unnamed enumerator data type. The enumerator constants for unnamed data type is January, February and March.

To assign a value to the month –

month = February;

Shortcoming of the unnamed enumeration types – we have to provide all the values of such data type at once. We can’t have multiple of those in a single code.

In conclusion, we have discussed enumeration in C.

Additional Info –

With the help of enumerator types, we can create our own data types. It also helps us to write a program in the most readable format.

Also, all the enumerator constants have a pre-defined value. The value of first constant in this case – January is 1, February is 2 and so on. Although, we can also specify other values as well.

Example 3.

enum month
{
     January = 4,
     February = 3,
     March,
};

Here, it is 3 for February, 4 for March which is same as that of January.

Worth mentioning here that, it is better is have unique values for all enumerator constants.

Similar Posts