What makes a better constant in C, a macro or an enum?

In terms of readability, enumerations make better constants than macros, because related values are grouped together. In addition, enum defines a new type, so the readers of your program would have easier time figuring out what can be passed to the corresponding parameter.

Compare

#define UNKNOWN  0
#define SUNDAY   1
#define MONDAY   2
#define TUESDAY  3
...
#define SATURDAY 7

to

typedef enum {
    UNKNOWN,
    SUNDAY,
    MONDAY,
    TUESDAY,
    ...
    SATURDAY,
} Weekday;

It is much easier to read code like this

void calendar_set_weekday(Weekday wd);

than this

void calendar_set_weekday(int wd);

because you know which constants it is OK to pass.

Leave a Comment