Google News
logo
Enumeration In C Language
Enumeration data type used to symbolize a list of constants with valid meaningful names, so that, it makes the program easy to read and modify. Enumeration has advantage of generating the values automatically for given list of names. Keyword enum is used to define enumerated data type.

Syntax : 
  enum type_name
  { 
   value1, value2... valueN 
   };

Here, type_name is the name of enumerated data type or tag. And value1, value2 ...valueN are values of type type_name.
By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer can change the default value.

  Program : The following program is an example of enumeration
#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main(){
enum week today;
 today=wednesday;
printf(“%d th day”,today+1);
return 0;
   }
Output :

4th day

Ambiguity Error :

There is one problem with enumeration, if any variable exist with same name in enumerator set in same scope then we get error at compile time.

  Example :
enum color{red, green, blue, white, yellow};
int red=0; 	// ambiguity error with red, so either one must be removed
void main()
{
int white=100; //preference is given to local variable, instead of e in enumeration
}
Output :

0 1 100 4

Explicit initialization of enumerators :

At the declaration of enumeration, we can give explicit values to the names and these values can be any integers. Even for two names, we can give the same value.

  Example :
enum month
{
jan=1, feb=2, mar=3, apr, may, june, july, aug, sep, oct, nov, dec;
};

Here names “jan”, “feb”, ”mar”, are assigned with values 1,2,3 respectively and remaining names are assigned with next succeeding number from the last value, that is 4, 5, 6… for the apr, may, june, july,….

Enumeration variables :

Using enumerator tag name, we can specify variables of its type. This makes the convenient and increases the readability of the program, the enumerator variables are nothing but unsigned int types.

  Example : <enum tagname> <varaiabel-1> [variable-2,variable-3,……];
enum  Color
{
Red=15, Green=26, Blue=13, White=5, Yellow=4, Grey=17;
};
void main()
{
enum Color wallcolor, floorcolor;
wallcolor=White;
floorcolor=Grey;
……………
……………
}