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

后端 未结 6 1155
栀梦
栀梦 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 13:46

    Note there are some differences between macros and enums, and either of these properties may make them (un)suitable as a particular constant.

    • enums are signed (compatible with int). In any context where an unsigned type is required (think especially bitwise operations!), enums are out.
    • if long long is wider than int, big constants won't fit in an enum.
    • The size of an enum is sizeof(int). For arrays of small values (up to say, CHAR_MAX) you might want a char foo[] rather than an enum foo[] array.
    • enums are integral numbers. You can't have enum funny_number { PI=3.14, E=2.71 }.
    • enums are a C89 feature; K&R compilers (admittedly ancient) don't understand them.

提交回复
热议问题