Enum in C Language
Categories: C language
The enum in C is also known as the enumerated type. It is a user-defined data type that consists of integer values, and it provides meaningful names to these values. The use of enum in C makes the program easy to understand and maintain. The enum is defined by using the enum keyword.
The following is the way to define the enum in C:
enum flag{integer_const1, integer_const2,.....integter_constN};
In the above declaration, we define the enum named as flag containing 'N' integer constants. The default value of integer_const1 is 0, integer_const2 is 1, and so on. We can also change the default value of the integer constants at the time of the declaration.
enum fruits{mango, apple, strawberry, papaya};
The default value of mango is 0, apple is 1, strawberry is 2, and papaya is 3. If we want to change these default values, then we can do as given below:
enum fruits{
mango=2,
apple=1,
strawberry=5,
papaya=7,
};
Enumerated type declaration
As we know that in C language, we need to declare the variable of a pre-defined type such as int, float, char, etc. Similarly, we can declare the variable of a user-defined data type, such as enum. Let's see how we can declare the variable of an enum type.
Suppose we create the enum of type status as shown below:
enum status{false,true};
Now, we create the variable of status type:
enum status s; // creating a variable of the status type.
In the above statement, we have declared the 's' variable of type status.
To create a variable, the above two statements can be written as:
enum status{false,true} s;
In this case, the default value of false will be equal to 0, and the value of true will be equal to 1.