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 :
Example :
enum month {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,DEC}; enum month rmonth;
- First Line Creates “User Defined Data Type” called month.
- It has 12 values as given in the pair of braces.
- In the second line “rmonth” variable is declared of type “month” which can be initialized with any “data value amongst 12 values”.
rmonth = FEB;
- Default Numeric value assigned to first enum value is “0”.
- Numerically JAN is given value “0”.
- FEB is given value “1”.
- MAR is given value “2”.
- APR is given value “3”.
- MAY is given value “4”.
- JUN is given value “5”.
- 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 ]
Similar to – [ Replace JAN , DEC with equivalent Numeric Code ]
for(i=0;i<=11;i++)
No comments:
Post a Comment