Enumerated Types
The C Language – Enumerated Data Types
An enumerated type is one whose values are symbolic
constants rather than literals.
Declaration example:
◦ enum Container_Type {CUP, PINT, QUART, HALF_GALLON,
GALLON};
Declaration of a variable of the above type:
◦ enum Container_Type milk_bottle;
Variables declared with an enumerated type are actually stored as integers.
Internally, the symbolic names are treated as integer constants, and it is legal to
assign them values, e.g.:
◦ enum Container_Type {CUP=8, PINT=16, QUART=32, HALF_GALLON=64,
GALLON=128};
◦ Otherwise, by default, CUP =0, PINT=1, QUART=2, etc.
Caution: don’t mix them indiscriminately with integers – even though it is
syntactically valid to do so.
◦ milk_bottle = -623; /*A bad idea, and likely to lead to trouble*/
◦ int a = PINT; /*Also a bad idea, and likely to lead to trouble*/
If there is only one declaration of variables of a particular
enumerated type (i.e. no type name), both statements may
be combined:
◦ enum {CUP, PINT, QUART, HALF_GALLON, GALLON} milk_bottle,
gas_can, medicine_bottle;
milk_bottle, gas_can, and medicine_bottle are now all
instances of the enum type, and all these variables can be
assigned CUP, PINT, etc.
No more variables of this type can be declared later
because no type name was given to it
Nor can pointers to this variable type be declared
#include
main() {
enum month {jan = 1, feb=2, mar=3, apr=4, may=5,
jun = 6, jul=7, aug=8, sep=9, oct=10, nov = 11,dec=12
} this_month;
this_month = feb;
printf(“month : %d\n”,this_month);
}
Output??
#include
main() {
enum month {jan = 1, feb=2, mar=3, apr=4, may=5,
jun = 6, jul=7, aug=8, sep=9, oct=10, nov = 11,dec=12
} this_month;
this_month = feb;
printf(“month : %d\n”,this_month);
}
Output:
month: 2