enum intro in C
Enums can be used to reduce #define statements in a C program, although they can have more uses.
Here is an example of enum.
#include
int main()
{
enum Days{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};
Days TheDay;
int j = 0;
printf("Please enter the day of the week (0 to 6)\n");
scanf("%d",&j);
TheDay = Days(j);
if(TheDay == Sunday || TheDay == Saturday)
printf("Hurray it is the weekend\n");
else
printf("Curses still at work\n");
return 0;
}
One thing to keep in mind is that enums start from 0 so in the following line of code
enum Days{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};
Sunday is assigned 0, Monday is assigned 1 and so on..
It is possible to make them start at a different number if we assign a number to it as shown below.
enum Days{Sunday = 1,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};
In the example above, Sunday would have the value 1, Monday would have 2 and so on….
Feel free to ask any questions in the comment box below.
Advertisement
Categories: OOP344