How to use Enum in C?

In C and C++, enum types can be used to set up collections of named integer constants. Consider a set of all days.

#define Sunday 0
#define Monday 1
#define Tuesday 2
#define Wednesday 3
#define Thursday 4
#define Friday 5
#define Saturday 6

The above lines can be replaced by:

1
enum AllDays{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

Example program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include "stdio.h" 
int main()
{
	enum AllDays{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
 
	AllDays aDay;
	int i = 0;
	printf("Please enter the day of the week (0 to 6)\n");
	scanf("%d",&i);
	aDay = AllDays(i);
 
	if(aDay == Sunday || aDay == Saturday)
	printf("It is weekend :) \n");
	else
	printf("It is not weekend :( \n");
 
	return 0;
}

One Response to “How to use Enum in C?”

  1. The statement “aDay = AllDays(i);” ie line no 10 in the above program is invalid and not allowed in C language

    Reply

Leave a Reply