Joined: Sun May 25, 2008 5:34 pm Posts: 95 Has thanked: 2 time Have thanks: 1 time
Code:
/* C enumerate type creates symbolic names. The names have integer values. */ #include <stdio.h>
/* This assigns the names Sun through Sat to the values 0 through 6. They are constants, and cannot be changed. It also defines the tag daynames which can be used to declare a variable of this type. */ enum daynames { Sun, Mon, Tue, Wed, Thu, Fri, Sat};
/* This just defines the names */ enum {SEC = 1, MIN = 60, HOUR = 60*60, DAY = 24*60*60};
int main() { /* Declare a variable of type enum daynames. It is really just an integer, of some size picked by the implementation large enough to hold all the enumeration values. */ enum daynames today;
/* This defines some names, each one taking the value one greater if than the last, if not given a specific value. The variable dd can hold any of the enumeratoin values. */ enum { DINK, DANK = 5, DUNK, DONGLE = 4, DANGLE, DROP } dd; int n;
/* Days of the week. These are just integer codes. */ for(today = Mon; today <= Fri; ++today) printf("%d ", today); putchar('\n');
/* Using the second value constants. */ printf("Three days, four hours, and 28 minutes is %d seconds.\n", 3*DAY + 4*HOUR + 28*MIN);
/* Enum type variables are just integers. Enum values are just integers. */ dd = 2; printf("%d %d %d %d %d %d %d\n", DINK, DANK, DUNK, DONGLE, DANGLE, DROP, dd); }
The identifier after the enum keyword (daynames for instance), is called in tag. In C++, it is also a type name, just as the name of a class. In plain C, it can be used with the enum keyword to create variables of the enumerated type.
Some languages, such as Pascal and Ada, contain a carefully designed and restricted enumerated type. The C version is much more flexible, or useless, depending on your viewpoint.