If you are interested in getting to know about the importance of enumeration in C language, follow this article’s guidance.
Importance of Enumeration in C (typedef enum)
Enums are useful in C to develop a user-friendly set of values which can be then used in the code. The first rule to define an enum is that no two values in an enum should be the same and the default values for an enum are integer values. Also, an enum can only be used inside the code base where they are defined and are not applicable if you try to apply them to an area where they are undefined.
The basic syntax to define an enum is:
To have a better understanding of enum, let’s follow a basic example in C:
Example 1
Output
Explanation
In the above example; enum “Day” is created with the name of all the Days included in it. Now, this enum Day can be used in the C code to declare a variable “today”:
In each enum, the first value is on index 0 and then 1,2,3 and so on. Index 0 value is always equal to zero by default, due to which if I have to print the day today it will be equal to today+1:
Example 2
enum fruit{Mango, kiwi, Orange, Fig, Apple, Guava, Pineapple,
Strawberry};
int main()
{
int i;
for (i=Mango; i<=Strawberry; i++)
printf("%d ", i);
return 0;
}
Output
Explanation
In Example 2, an enum of fruit names is created and then a for loop is run to print the enum starting from the state Mango (0) to the state Strawberry (7).
By the above-stated examples, you can see how by using an enum one can design a particular data-type set which can then be used in the code to perform the desired operation.
Key Points
- Enum always includes values which are related somehow.
- Enum is important for developers and programmers to create their own data types for their applications and other programs.
- Enum provides great customization in Programs, as enum can be defined with any name.
- Remember that each value in the enum should be unique.
- An enum can only be used inside the code base.
Conclusion
Enum is a set of values that are customizable. While writing a C code user can define any enumeration variable like fruit, day, or month and then it can be used to declare variables or to perform multiple operations in a code.