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
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.
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.