C enum : Enumerated Types



Enum [Enumerated] : User defined Data Type in C

Syntax:

enum identifier {value1, value2,.... Value n};
  • enum is ” Enumerated Data Type “.
  • enum is user defined data type
  • In the above example “identifier” is nothing but the user defined data type .
  • Value1,Value2,Value3….. etc creates one set of enum values.
  • Using “identifier” we are creating our variables.

Let’s Take Look at Following Example …
Example :

enum month {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,DEC};
enum month rmonth;
  1. First Line Creates “User Defined Data Type” called month.
  2. It has 12 values as given in the pair of braces.
  3. In the second line “rmonth” variable is declared of type “month” which can be initialized with any “data value amongst 12 values”.
rmonth = FEB;
  1. Default Numeric value assigned to first enum value is “0”.
  2. Numerically JAN is given value “0”.
  3. FEB is given value “1”.
  4. MAR is given value “2”.
  5. APR is given value “3”.
  6. MAY is given value “4”.
  7. JUN is given value “5”.
  8. and so on…..
printf("%d",rmonth);
  • It will Print “1” on the screen because “Numerical Equivalent” of  “FEB” is 1 and “rmonth” is initialized by “FEB”.
  • Generally Printing Value of enum variable is as good as printing “Integer“.

Sample Program :

#include< stdio.h>
void main()
{
int i;
enum month {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,DEC};
clrscr();
  for(i=JAN;i<=DEC;i++)
      printf("\n%d",i);
}

Output :

01234567891011

Consider –

for(i=JAN;i<=DEC;i++)

Above Statement is
Similar to – [ Replace JAN , DEC with equivalent Numeric Code ]

for(i=0;i<=11;i++)