Portability question
BALDWIN
mike at whuxl.UUCP
Sat Nov 9 16:38:44 AEST 1985
> ...
> You have an array of seven structures, one for each day of the week.
> You often process these structures as an array, but sometimes, you
> want to just deal with one of them. And you'd like clear, mnemonic names
> to add the reader of your code.
> So, how about this:
> #define MONDAY 0
> #define TUESDAY 1
> ...
> #define SUNDAY 6
> struct x a[SUNDAY + 1];
>
> then you can do:
> for(i = Monday; i <= Sunday; i++) {
> a[i].whatever = something;
> }
> but you can also say:
> a[MONDAY].whatever = something;
This is where enums could actually be useful:
typedef enum {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY,
MAXDAY
} day_t;
struct x a[MAXDAY];
day_t d;
for (d = 0; d < MAXDAY; d++)
a[d].whatever = something
Now you don't have to give numbers to the days, or know what the names
of the first or last days are, and with MAXDAY, you can declare arrays
and loop over the values. One slight problem, though. This code gives
warnings from cc. <, ++, and [] are all frowned upon if used with enums
(but the array declaration slips by...). I consider this a massive mistake
in the implementation of enums, making them virtually useless. You can't
even loop over them! Anyway, ANSI C fixes this; enums are treated just
like any other integers.
--
Michael Baldwin
{at&t}!whuxl!mike
More information about the Comp.lang.c
mailing list