Home > OOP344 > enum intro in C

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.

Categories: OOP344
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: