Enumeration (enum) in C

An enumeration (enum) is a special class that represents a group of constants. It is used to assign names to the integral constants which makes a program easy to read and maintain.

The enum keyword is used to create an enum. The constants declared inside are separated by commas.

For example, Sunday, Monday, Tuesday, Wednesday are the names of four days. Thus, we can say that these are of types days. Therefore, this becomes an enumeration with name Days and Sunday, Monday, Tuesday, Wednesday as it’s elements.

Syntax:

enum enum_name {
    element1,
    element2,
    element3,
    element4,
};

Now let’s define an enum of the above example of Days.

enum Days {
    Sunday,
    Monday,
    Tuesday,
    Wednesday 
}D;
OR
enum Days {
	Sunday,
	Monday,
	Tuesday,
	Wednesday 
}
int main() {
	enum Days D;
}

Here, all the elements of an enum have a key value. By default, the value of the first element is 0, that of the second element is 1 and so on.

So for the declaration: enum Days {Sunday, Monday, Tuesday, Wednesday} the values will be assigned like Sunday=0, Monday=1, Tuesday=2, Wednesday=3.

Let us understand this with an easy code as below:

/* C programs to understand how enum works */
/* www.codewindow.in */

#include <stdio.h>

enum Days {
	Sunday,
	Monday,
	Tuesday,
	Wednesday
};

int main() {
	enum Days D;
	D = Tuesday;
	printf("%d\n",D);
	return 0;
}

Output: 2

Explanation: As the Tuesday element in the enum has an key or, order value = 2 so we get 2 as the output.


You Missed

Also Checkout