Enumeration (enum) In C Programming

Enumeration or enum is a user-defined custom type that is used to create enumerable data types in C. By using the enumeration the created structures are became easy to read other than using hard to read code. In order to create enum the enum keyword is used where the enumeration name of the enum is provided and values are provided inside curly brackets.

Enumeration (enum) Syntax

The enumeration type has the following syntax.

enum NAME{CONST1,CONST2,...};
  • enum keyword is used to define enumeration type
  • NAME is the name of the enumeration
  • CONST1,CONST2,… are constants are used to create constants.

Create Enum

Creating an enum is very easy. The enum definition is generally located after the library import in the first lines of the source code. In the following example, we create an enum that describes two states named Enabled and Disabled .

#include<stdio.h>

enum state{Enabled,Disabled};

int main()
{
   enum state computer_state;
   computer_state = Enabled;
   return 0;
}

Print Enum Value

Every enum has an integer value where these values are assigned to the enum contents implicitly. These values start from 0 where the first constant value is 0 and other constants get values 1,2,3 in a row.

#include<stdio.h>

enum numbers{Zero,One,Two,Three,Four};

int main()
{
   enum numbers a;
   a = Three;
   printf("%d",a);
   return 0;
}

Month Enum Example

One of the most popular use cases for the enum or enumeration type is creating months of the year with their names.

#include<stdio.h>

enum month{Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Now,Dec};

int main()
{
   enum month m;
   m = Jan;
}

Week Days Enum Type

Another popular enumeration use case is using weekdays.

#include<stdio.h>

enum month{Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};

int main()
{
   enum month m;
   m = Jan;
}

Assign Value For Enum Constants

By default, enum constants get values starting from 0 and increasing 1 by 1. But we can also specify specific values to the enum constants by using equal signs.

#include<stdio.h>

enum numbers{Zero=0,Five=5,Ten=10};

int main()
{
   enum numbers a;
   a = Ten;
   printf("%d",a);
   return 0;
}

Leave a Comment