enumerated data type in C Language - WBUT MCA 2011
softetechnologies
10-12-2019    150 times
enumerated C Language WBUT MCA

What do you mean by enumerated data type in C ? Explain with an example. [WBUT MCA 2011]

Enumeration (or enum) is a ADT (Abstruct Data Type) or user defined data type in C. Enumeration is assign names (String) to its corresponding integral constants. For example, if we use multiple colors in our program, then we can assign the color name with the color code. Because colors name is easy to handle by the user but C language works with color codes.

To declare an enumeration types in C language, we use a specific keyword called ‘enum’. Following is an example of enum declaration.

enum Colors{RED,GREEN,BLUE,YELLOW}; 
int main() 
{ 
   int i; 
   for (i=RED; i<=YELLOW; i++)       
   {   
          printf("%d ", i);
   }
   return 0; 
}

Output: 0 1 2 3

Note:

By default, in enumeration types, index start with 0 and increase 1 by each item.

But we can use any random value for the items. And also we can assign same number for the different item.

enum Colors{RED=4,GREEN=10,BLUE=5,YELLOW=9}; 
int main() 
{ 
   int i; 
   for (i=RED; i<=YELLOW; i++)
   {  
        printf("%d ", i);
   }
   return 0; 
}

Output:4 10 5 9

We can assign values to some item of enum in any order. All unassigned names get value as value of previous name plus one.

Private Teacher
enum Colors{RED=4,GREEN=10,BLUE,YELLOW=9}; 
int main() 
{ 
   int i; 
   for (i=RED; i<=YELLOW; i++)
   {  
        printf("%d ", i);
   }
   return 0; 
}

Output:4 10 11 9

Each enum item must be unique in a scope

enum fontColors{RED,GREEN,BLUE,YELLOW}; 
enum backcolor{CYAN,BLACK,RED,WHITE};
  
int main(){return 0;} 

Output: It generates an error because RED is declared twice in the scope. Both item are declared in different enum variable, but it is also not allowed.

softetechnologies
softetechnologies
    Author Details
Arnab De
I have over 16 years of experience working as an IT professional, ranging from teaching at my own institute to being a computer faculty at different leading institute across Kolkata. I also work as a web developer and designer, having worked for renowned companies and brand. Through tutorialathome, I wish to share my years of knowledge with the readers.
    Related Post
  Query About the post