enum in C
Enumeration in C
- Enumeration (or enum) is a user-defined data type in C. It is mainly used to assign names to integer constants, the names make a program easy to read and maintain.
- The keyword enum is used to declare an enumeration
- syntax of enum.
enum enum_name {cons1, cons2, ... };
- The enum keyword is also used to define the variable of the enum type. There are two ways to define the variables of enum types as follows.
- Declaration:
enum week {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
enum week day; //initialization
- Now in the above declaration Monday is assigned to 0, Tuesday is assigned to 1, Wednesday to 2, and so on at the and Sunday is assigned to 6. Compiler By default assigns values starting from 0.
Example to understand the working of enum in C.
#include<stdio.h>
enum week {Mon, Tue, Wed, Thus, Fri, Sat, Sun};
int main()
{
enum week day;
day=Fri;
printf("%d", day);
return 0;
}
Output:
4
- In above example the day variable is declared and valus=e of "Fri" is allocated to day, which is 4.
- So as a result we get 4 as printed.
Second example of enum.
#include<stdio.h>
enum months { Jan, Feb, Mar, Apr, May, Jun, July, Aug, Sep, Oct, Nov, Dec};
int main()
{
int i;
for(i=Jan; i<=Dec ; i++)
{
printf("%d",i);
}
return 0;
}
Output: 0 1 2 3 4 5 6 7 8 9 10 11
- In above example The loop run from 0 to 11, because the value of Jan is 0 and Value of Dec is 11
- You can also assign your own values to enum names and they can have same value but you can only assign a integer value to the enum names
For example
enum result {pass=1, failed=0, present=1, absent=0};
- Compiler always assigned names values as value of previous name plus one:
Example:
#include<stdio.h>
enum day {Sunday=1, Monday, Tuesday=7, Wednesday, Thursday=10, Friday, saturday};
int main()
{
printf("%d %d %d %d %d %d %d ",Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday);
return 0;
}
Output: 1 2 7 8 10 11 12
- All enum constants must be unique in their scope.
For example:
enum student {Student_1, Student_2, Student_3};
enum std {Student_2, Student};
- it gives error: "Student_2" has a previous declaration as 'state failed'.
Note: enum variables has local scope, but Mario has global scope.