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

Varun Chhangani picture Varun Chhangani · Jun 15, 2013 · Viewed 26.9k times · Source

I am confused about when to use macros or enums. Both can be used as constants, but what is the difference between them and what is the advantage of either one? Is it somehow related to compiler level or not?

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Jun 15, 2013

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.