Enum in C
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.
Fig: enum in c |
The following is the way to define the enum in C:
enum flag{integer_const1, integer_const2,.....integter_constN};
For example:
enum fruits{mango, apple, strawberry, papaya};
we can write this also default value
enum fruits{
mango=2,
apple=1,
strawberry=5,
papaya=7,
};
Enumerated type declaration
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.
we create the enum of type status:
enum status{false,true};
Now, we create the variable of status type:
enum status s;
To create a
variable, the above two statements can be:
enum status{false,true} s;
Simple program of enum
#include <stdio.h>
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday , Saturday};
int main()
{
enum weekdays w;
w=Monday;
printf("The value of w is %d",w);
return 0;
}
Output
The value of w is 2
….program finished with
exit code 0 press enter to exit console.
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.
we create the enum of type status:
enum status{false,true};
Now, we create the variable of status type:
enum status s;
To create a
variable, the above two statements can be:
enum status{false,true} s;
Simple program of enum
#include <stdio.h>
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday , Saturday};
int main()
{
enum weekdays w;
w=Monday;
printf("The value of w is %d",w);
return 0;
}
Output
The value of w is 2
….program finished with
exit code 0 press enter to exit console.
No comments:
Post a Comment