It is frequently desirable to have subscripts which are represented by labels instead of numeric values.
This can be done with the #define compiler directive to establish items which are very much like Pascal constants. However, this can lead to long tedious lists at the beginning of a program.
C provides another method -- a programmer-defined type called an enumeration. This is a set of integer constants that are represented by identifiers, the usual alphanumeric ones used for variables. The keyword enum is used to introduced a named list such as the following one for the days of the week.
enum days { SUN, MON, TUES, WED, THURS, FRI, SAT };
As usual, things in C normally start with the zeroth item, so SUN is equivalent to 0 and SAT to 6 in the above example. But this can be overridden as is done below by specifying that the beginning item should be considered the first. The remaining ones would then represent the values 2 through 7.
enum days { SUN = 1, MON, TUES, WED, THURS, FRI, SAT };
Variables can then be declared to be of this type, e.g.:
enum days day;
The use of the enum type permits loops to be defined such as the following.
for (day = SUN; day <= SAT; day++)
The output below can be produced by either of the two programs which follow.
1 Sunday 2 Monday 3 Tuesday 4 Wednesday 5 Thursday 6 Friday 7 Saturday
Since SUN is assigned the default value 0, to print out the numbers of the days of the week, day has 1 added to it in the printf() call.
#include <stdio.h>
enum days { SUN, MON, TUES, WED, THURS, FRI, SAT };
main()
{
enum days day;
char *dayName[SAT + 1] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
for (day = SUN; day <= SAT; day++)
printf("%d%11s\n", day + 1, dayName[day]);
return 0;
}
Since SUN is assigned the value 1, a null string needs to be placed at the beginning of the dayName array so that the numbers match up with the days of the week in the expected fashion.
#include <stdio.h>
enum days { SUN = 1, MON, TUES, WED, THURS, FRI, SAT };
main()
{
enum days day;
char *dayName[SAT + 1] = {"", "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
for (day = SUN; day <= SAT; day++)
printf("%d%11s\n", day, dayName[day]);
return 0;
}
N.B. Although SAT + 1 is specified as the size of the dayName array in both programs, this could be eliminated, because the default declaration would be sufficient.