Enumeration (or enum)
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants,
the names make a program easy to read and maintain.
Example:1
An example program to demonstrate working
#include <stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}
Output:
2
--------------------------------
Process exited after 0.03745 seconds with return value 0
Press any key to continue . . .
Example:2
Another example program to demonstrate working of enum in C
#include <stdio.h>
enum year{Jan, Feb, Mar, Apr, May, Jun, Jul,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
--------------------------------
Process exited after 0.04998 seconds with return value 0
Press any key to continue . . .
Example:3
Interesting facts about initialization of enum.
#include <stdio.h>
enum State {Working = 1, Failed = 0, Freezed = 0};
int main()
{
printf("%d, %d, %d", Working, Failed, Freezed);
return 0;
}
Output:
1, 0, 0
--------------------------------
Process exited after 0.03936 seconds with return value 0
Press any key to continue . . .
Example:4
If we do not explicitly assign values to enum names, the compiler by default assigns values starting from 0.
For example, in the following C program, sunday gets value 0, monday gets 1, and so on.
#include <stdio.h>
enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum day d = thursday;
printf("The day number stored in d is %d", d);
return 0;
}
Output:
The day number stored in d is 4
--------------------------------
Process exited after 0.04111 seconds with return value 0
Press any key to continue . . .
Example:5
We can assign values to some name in any order. All unassigned names get value as value of previous name plus one.
#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5,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 5 6 10 11 12
--------------------------------
Process exited after 0.04021 seconds with return value 0
Press any key to continue . . .
Example:6
The value assigned to enum names must be some integeral constant, i.e.,
the value must be in range from minimum possible integer value to maximum possible integer value.
All enum constants must be unique in their scope. For example, the following program fails in compilation.
enum state {working, failed};
enum result {failed, passed};
int main() { return 0; }
Output:
Compile Failed
--------------------------------
Process exited after 0.8577 seconds with return value 15
Press any key to continue . . .