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

后端 未结 6 1163
栀梦
栀梦 2020-12-02 13:32

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 someho

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 14:06

    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.

提交回复
热议问题