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;
}
Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in