What are enums actually?
Enums provide an opportunity to the user to define a shorthand for fixed set of constants like months in a year, gender etc. Enumeration is the list of constant integer values, which means that the enum values can’t be modified.
Here we are going to explain Enumeration usage rules and constraints in C language.
In C Enums are defined by enum keyword. The enum definition is analogous to the way a structure is defined .
Syntax:
enum tagname{CONST1=1,CONST2,…} enumVariable;
tagname – It is the name given to the enum and it is optional to provide it or not.
{CONST1=1,CONST2,…} – Set of string literals representing the constants. Each element is equal to integral value starting with 0,the next 1 and so on, unless explicitly defined by the user like CONST1=1. In this case the values of the elements after the explicitly defined element are in consecutive order of its value. For example if CONST2=6 then values of the elements after it will be 7,8,9 and so on respectively.
enumVariable – It is the list of variables of enum type, as the enum is of integral type so are these variables. These variables can be assigned any integer values other then the enum constants also. It is optional to use these variable(s). We may also define these variables later in the program as follows:
enum tagname enumVariable;
Here is a sample program that uses enums
#include <stdio.h> //Defining the enum enum week { MONDAY= -1,TUESDAY,WEDNESDAY,THURSDAY=6,FRIDAY,SATURDAY,SUNDAY }; int main(void) { //Declaring an enum in the program enum week day=FRIDAY; switch(day) { case MONDAY: printf("Monday Sucks"); break; case SATURDAY: printf("Weekends are fun"); break; case SUNDAY: printf("Weekends are fun"); break; default: printf("It depends on the mood :D %d",day); break; } return 0; }
Here is the running link of the program:- http://ideone.com/EKe6DO