An Enumerated data type consists of an ordered set of distinct constant values defined in a data type in a program. The format of en-um is:-
where., name is the name of the enumerated data type, also known as tag and value-1,value-2,value-3,…….,value-n are values that variable of type name can take.
Example (1) : -
This declaration states that a variable of type fruit can have any of the four values namely apple, orange, mango and pineapple, but no other value. Once the type fruit has been defined then variable of that type can be defined in the following manner :-
Now, the variable a and b are of type fruit and can assume value from the list : (apple, orange, mango, pineapple).
Example (2) : -
Part-1 enum days
Part-2 days holiday,wdays;
The first part defines an enumeration named days . The second part declares the variables holiday and wdays to be enumeration variable of type days. Thus each variable can be assigned any one of the constants mon,tue,wed,thu,fri,sat,sun.
The two parts in example-2 can be combined if desired, resulting in
or without the name(tag) , simply
Enumeration constants are automatically assigned equivalent integer values, beginning with 0 for the first constant, with each successive constant increasing by 1. Therefore in example-1, the enumeration constants will represent the following integer values: -
These automatic assignments can be overridden by assigning explicit integer values which differ from the default values. Those constants are not assigned explicit values will automatically be assigned values which increase successively by 1 from the last explicit assignment.
Operations on Enumerated Data Types
example : - holiday=sun;
Comparing using Relational Operators
Example : -
Consider the enumerated data types defined in
previous example: -
Advantages of Enumerated Data Types
Simplifies the Program.
enhances the readability of the program.
Help to locate more errors at the compile time.
Helps us to express a program in a more natural way.
Redefining Data Types with typedef
In c, it is possible to redefine the built-in as well as user defined data types. This task is accomplished by the typedef statement.
typedef type new_type;
where typedef is keyword, type is either built-in data type or user-defined data type, and new_type is the new name of the type.
typedef float real;
This statement redefines the data types float to real. Then to declare x,y and z of type float, we can also write