An enum, short for enumeration, is a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type. It is a user-defined data type that is used to assign names to integral constants, making a program easy to read and maintain. Enums are commonly used in programming languages such as C, C++, C#, Java, and Rust.
An enum variable type can be found in C, C++, and C#, and it encapsulates all possible values from a specific group. In C, an example of an enum is:
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
In this example, the variable day
is declared as the variable, and the value of Wed
is allocated to day
, which is 2. So as a result, 2 is printed.
In C#, an example of an enum is:
enum Season { Spring, Summer, Autumn, Winter }
By default, the associated constant values of enum members are of type int; they start with zero and increase by one following the definition text order. You can explicitly specify any other integral numeric type as an underlying type of an enumeration type. You can also explicitly specify the associated constant values.
Enums are useful when a variable can take certain values, and it is useful to use enums to encapsulate all possible values from a specific group. They make the code more readable and maintainable.